From e3c3b2cbb73268dcd1e328c8befe2601260e0f2d Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 07:09:37 +0100 Subject: [PATCH 01/15] implement DEV workspace and project automation authority --- ...hell and Workspace Layout Specification.md | 5 +- .../10. DEV and Automation Specification.md | 357 +++++++++++++ ...roject-Local Studio State Specification.md | 2 + ... and Adapter Architecture Specification.md | 43 +- docs/specs/studio/README.md | 12 +- prometeu-app/build.gradle.kts | 12 + .../app/StudioApplicationConfiguration.java | 46 +- .../operation/ExecutorOperationExecutor.java | 19 +- .../java/p/studio/app/DevDesktopTest.java | 146 ++++++ .../ExecutorOperationExecutorTest.java | 33 ++ .../api/automation/AutomationOutcome.java | 7 + .../api/automation/AutomationSession.java | 20 + .../api/automation/AutomationSnapshot.java | 12 + .../api/automation/CanonicalCapture.java | 12 + .../automation/ControlDeniedException.java | 10 + .../studio/api/automation/ControlResult.java | 6 + .../p/studio/api/automation/ControlState.java | 2 + .../api/automation/DocumentHandoff.java | 10 + .../automation/ManagedHeadlessSession.java | 8 + .../p/studio/api/automation/ManualLease.java | 7 + .../studio/api/automation/ProjectAccess.java | 17 + .../p/studio/api/automation/TaskIdentity.java | 9 + .../studio/api/operation/OperationHandle.java | 5 + .../p/studio/api/session/ProjectSession.java | 2 + .../FileSystemAssetWorkspaceStorage.java | 21 +- .../core/assets/PackerAssetCatalog.java | 38 +- .../core/assets/PackerAssetCommands.java | 74 ++- .../core/assets/PackerAssetPacking.java | 10 +- .../metadata/AssetStudioMetadataService.java | 42 +- .../scene/SceneBankWorkflowService.java | 10 +- .../tiled/TiledAssetGenerationService.java | 480 +++++++++--------- .../DefaultExecutionControllerFactory.java | 7 +- .../PlayStopExecutionController.java | 30 +- .../core/project/ProjectAccessRegistry.java | 42 ++ .../session/DefaultAutomationSession.java | 243 +++++++++ .../core/session/DefaultProjectSession.java | 13 +- .../session/DefaultProjectSessionFactory.java | 14 +- .../core/shipper/StudioShipperService.java | 8 +- .../core/assets/AssetAuthorityTest.java | 51 ++ .../PlayStopExecutionControllerTest.java | 32 ++ .../session/DefaultAutomationSessionTest.java | 185 +++++++ .../session/DefaultProjectSessionTest.java | 6 +- .../core/support/ControlledOperations.java | 37 ++ .../controls/forms/StudioFormSection.java | 16 + .../studio/ui/javafx/utilities/i18n/I18n.java | 7 + .../p/studio/ui/javafx/window/MainView.java | 26 +- .../StudioWorkspaceLifecycleSupport.java | 11 +- .../ui/javafx/workspaces/WorkspaceId.java | 3 +- .../workspaces/assets/AssetWorkspace.java | 2 + .../assets/details/AssetDetailsControl.java | 58 +++ .../AssetDetailsBankCompositionControl.java | 4 + .../contract/AssetDetailsContractControl.java | 8 +- ...AssetDetailsPaletteOverhaulingControl.java | 4 + .../AssetDetailsColorSchemaGroupsControl.java | 6 + .../assets/list/AssetListControl.java | 2 + .../javafx/workspaces/dev/DevWorkspace.java | 108 ++++ .../dev/DevWorkspaceProjection.java | 16 + .../workspaces/dev/ManualProjectUiGuard.java | 48 ++ .../main/resources/i18n/messages.properties | 17 + .../resources/i18n/messages_pt_BR.properties | 17 + .../resources/themes/default-prometeu.css | 5 + .../dev/DevWorkspaceProjectionTest.java | 31 ++ 62 files changed, 2180 insertions(+), 354 deletions(-) create mode 100644 docs/specs/studio/10. DEV and Automation Specification.md create mode 100644 prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java create mode 100644 prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java create mode 100644 prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java create mode 100644 prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java create mode 100644 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java create mode 100644 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java create mode 100644 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java create mode 100644 prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java diff --git a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md index d73e6496..2aaf24e7 100644 --- a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md +++ b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md @@ -6,7 +6,7 @@ Purpose: Define the normative shell structure of the Studio UI. ## Authority and Precedence -This specification consolidates the accepted Studio shell decision into normative form. +This specification consolidates the accepted Studio shell decision into normative form. DEC-0060 adds DEV and project-scoped automation authority; its detailed behavior is owned by the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md). ## Normative Inputs @@ -46,10 +46,13 @@ The baseline workspace set includes: - Asset Management; - Debugger/Profiler; +- DEV, for granting/reclaiming project control and observing external-agent automation; - Shipper, temporarily represented by the current `BuilderWorkspace`. `BuilderWorkspace` is transitional and must not be treated as a long-term architectural reference for the final shipping surface. +DEV MUST remain separate from human Debug and MUST NOT offer chat or manual Play/input for the headless session. Selecting, hiding or switching away from DEV MUST NOT grant or release project authority. The shell's always-visible run surface remains visible, but conflicting manual actions MUST be unavailable while project control is ceded, including while waiting for an agent. Services MUST enforce the same exclusion; shell bindings alone are insufficient. + ## Workspace Architecture Model The shell-level workspace host exists to mount independently authored workspaces under one Studio contract. diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md new file mode 100644 index 00000000..a256fdb8 --- /dev/null +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -0,0 +1,357 @@ +# DEV and Automation Specification + +## Status + +Active normative baseline; implementation is delivered in ordered phases. +This status does not claim that the DEV workspace, MCP endpoint or integrated +agent loop is already available in an installed Studio. + +## Scope and Ownership + +Owner: **studio**, including neutral API/Core services, the JavaFX DEV workspace +and application/infrastructure adapters. Runtime owns execution and its external +headless protocol. Compiler, language/SDK references, LSP and Packer retain their +existing domain ownership. + +## Purpose + +Allow a developer to grant control of an open project to an external coding +agent, observe managed operations and canonical runtime images, and explicitly +reclaim control. Studio provides specialized project services through MCP, not +an embedded agent or a second editor. + +## Authority and Normative Inputs + +This specification implements accepted **DEC-0060**, including D1–D7 and B1–B9. +PLN-0139 sequences its implementation; it does not redefine this contract. + +- [Core and Adapter Architecture](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md): dependency direction, composition and shared operations. +- [Shell and Workspace Layout](1.%20Studio%20Shell%20and%20Workspace%20Layout%20Specification.md): workspace mounting and project lifetime. +- [Project-Local State](8.%20Project-Local%20Studio%20State%20Specification.md): configuration and restoration exclusions. +- [Runtime Headless Automation Protocol](../../../../runtime/docs/specs/runtime/11a-headless-automation-protocol.md): runtime-owned wire, commands, framing, limits and execution meanings. + +MUST, MUST NOT and MAY express requirements, prohibitions and permissions. +Implementation MUST NOT weaken this accepted baseline; substantive ambiguity +requires explicit decision review rather than a guessed implementation rule. + +## 1. Shared Services and Protocol Boundaries + +JavaFX and MCP MUST consume the same neutral API/Core authority, sessions, +operations and orchestration. Neither adapter MAY simulate UI actions or +implement a parallel permission/build/pack/execution system. + +| Boundary | Owner and responsibility | +| --- | --- | +| Studio API | Plain-Java contracts, identities, snapshots, typed outcomes, diagnostics and ports; no toolkit, framework or concrete wire DTOs | +| Studio Core | Project/session authority, guards, operations, build/pack/runtime coordination and ordered cleanup; testable without JavaFX or Spring | +| JavaFX DEV | Human grant/reclaim actions, presentation, localization, canvas, subscriptions and FX-thread projection | +| Application/infrastructure | MCP HTTP transport, process supervision, runtime JSONL translation, existing project LSP client, lifecycle and packaging | +| Runtime | Firmware/VM execution, input sampling, logical frames, ticks, rendering, watchdogs and faults | +| External coding client | Agent/chat, model/provider credentials, native file editing, budget, iterations and simple task stopping criteria | + +MCP Streamable HTTP, runtime JSONL/stdio, and human Debug/DevTools MUST remain +distinct protocols with distinct lifecycles. A native Rust/Java binding is not +the chosen runtime boundary. Compiler, LSP, Packer and runtime semantics MUST +NOT be reimplemented in Studio. + +The functional dependency graph in spec 9 MUST remain unchanged. Services +requiring guards MUST receive shared authority through neutral contracts and +composition, not depend on concrete session implementations or UI state. + +## 2. Project Authority and Control States + +Authority MUST belong to an open project session, not a tab, focused window, +HTTP connection or UI component. The agent MUST supply a project root; Studio +MUST validate it against an open project and use explicit project identity. +Window focus MUST NOT implicitly select a call's target. + +Connection authentication, human project grant and task control identity MUST +be separate checks. At most one task MAY own a project's grant. Acquisition +without a prior human grant MUST fail. A task identity MUST be required for +authorized work and MUST NOT be reusable for another project or revoked task. + +| State | Admission and permitted behavior | Exit | +| --- | --- | --- | +| Manual control | Human editing/Debug; grant only with no active Debug or conflicting managed work, and successful document handoff | Human grant enters waiting | +| Waiting for agent | Grant already blocks conflicting manual work; authenticated agent can acquire; human can reclaim without an agent connection | Acquisition enters working; reclaim enters returning | +| Agent working | One acquired task uses its valid identity; developer can inspect, navigate and reclaim | Explicit task release or human revoke enters returning | +| Returning control | Prior authority is invalid; stop managed work and refresh documents; manual conflicting actions remain blocked | Manual control only after cleanup/handoff | + +Grant and acquisition MUST be enforced atomically with conflicting operation +admission. Concurrent acquisition MUST NOT create two owners. Project-local +authority MUST NOT become a global Studio lock. + +Human Debug active MUST prevent grant. From grant onward, including waiting +and silence, Studio MUST prevent manual editing, Debug, build and other +conflicting project mutation. Guards MUST apply at service entry points as +well as UI bindings. Navigation, inspection and monitoring remain available. + +An operation finishing, failing compilation, raising a guest fault or losing +its runtime session MUST NOT release task authority. Silence, client +disconnection and waiting MUST NOT cause expiration or automatic resumption. +There is no heartbeat or silence timeout in this baseline. + +## 3. Grant and Saved-Document Handoff + +Grant MUST cover Studio-owned unsaved buffers/drafts, including dirty asset +editing surfaces; it MUST NOT assume that source files are the only editable +project content. + +If such content is dirty, DEV MUST offer **Save all and grant** or **Cancel**. +Grant MUST follow successful saves; user cancellation or save failure MUST NOT +cede control. Clean projects do not require a code snapshot, clean Git tree or +commit. Document participants MUST use neutral handoff contracts without moving +presentation buffers or JavaFX types into Core. + +The agent edits the actual project folder with native external tools. Build +MUST use saved files, and the existing project LSP client MUST synchronize +saved content before semantic queries. Studio MUST NOT claim to save external +unsaved buffers or protect against concurrent external writes. + +On authority return, Studio MUST refresh open documents from disk and MUST NOT +reapply stale buffers over agent changes. Revocation/cancellation MUST preserve +edits already made. There is no later Apply/merge step or Studio-owned code +rollback. Review, integrity, Git commits and recovery remain developer duties. + +SDK/external libraries MUST be consultable but MUST NOT be edited by the +game-authoring task. Editable local libraries MUST be inside project scope. +Unsupported capabilities or required SDK changes MUST be reported as limitations, +not silently implemented outside that scope. This does not prohibit the runtime +engineering delivery that prepared this integration. + +## 4. Return, Revocation and Closure + +Explicit release and human reclaim MUST follow this order: + +1. Invalidate task authority and reject new or delayed calls under the old identity. +2. Cancel/stop managed work and shut down owned runtime processes. +3. Refresh open documents from saved project content, without stale writeback. +4. Release conflicting manual operations and present manual control. + +Late completions MUST NOT resurrect a revoked task or restore its authority. +Cleanup MUST NOT advertise manual control before managed work is stopped and +document refresh is complete. Diagnostics MUST distinguish cleanup failure from +a successful return; operation outcome and authorization state are not the same. + +Reclaim MUST also work while waiting for an agent or after an operation failure. +Another task MUST require a new human grant. Closing/hiding/switching DEV MUST +NOT release control. Closing the project or Studio MUST revoke authority and +stop managed processes before teardown of their providers/executors. Reopening +MUST start in manual control, even when restoring DEV as the selected workspace. + +Studio cannot stop direct writes by the external coding client. The UI and +connection instructions MUST tell the developer to stop that client separately; +reclaim is not an operating-system filesystem lock or a rollback guarantee. + +## 5. DEV Workspace Contract + +DEV MUST expose: + +- **Grant control to AI** (`Ceder controle à IA`) and **Interrupt and reclaim control** (`Interromper e retomar controle`); +- the four control states, project identity, current managed operation and diagnostics; +- a canonical-image canvas with session/build/logical-frame/render-frame identity and stale status; +- a short history of Studio calls, not an independent code history; +- **Copy MCP configuration**, plus short connection/use instructions when the real MCP composition is available. + +Actions MUST reflect shared service authority. DEV MUST NOT own a duplicate +lock or release authority when disposing visual subscriptions. Presentation +updates MUST follow the existing FX-thread, theme, localization and workspace +lifecycle rules. + +DEV MUST NOT contain chat, provider settings, manual headless Play/input or +concurrent human control of the agent's execution. Human play/testing remains +in Debug with its existing host/protocol/lifecycle, subject to symmetric guards. +“Agent working” means the task has been acquired; it is not a claim to observe +all external edits, reasoning or conversation. + +Without a real composed MCP endpoint, configuration copy MUST be unavailable +rather than produce a fabricated endpoint or token. Test doubles MAY supply +operations/captures to isolated tests, never masquerade as product execution. + +## 6. Operations and Lost Responses + +Automation MUST reuse the neutral operation executor/handle boundary: stable +operation identity, observable snapshots/progress, cancellation, asynchronous +completion and typed results. Build/pack diagnostics MUST be preserved. +Success, lifecycle termination, guest fault, infrastructure/host failure and +cancellation MUST remain distinguishable, including known partial progress. + +Build and advance starts MUST return `operationId` promptly. Each start MUST +accept `clientRequestId` and allow authorized lookup by that identity if the +initial response is lost. Within the task: + +- same identifier and same parameters MUST return the existing operation without reexecution; +- same identifier with different parameters MUST fail; +- deduplication and lookup MUST still validate project/task authority; +- the registry MUST stay in memory only, without restart recovery or replay. + +Runtime `requestId` correlates a wire call; it is not Studio operation +deduplication. Neither transport error nor lost response authorizes blindly +retrying an advance. A runtime crash requires an explicit new session, not +restoration/replay; task authority remains governed by section 2. + +## 7. Runtime Supervision and Canonical Capture + +Studio MUST resolve `prometeu headless --stdio` from the configured runtime +installation. It MUST NOT discover/download another runtime over the network. +Missing or incompatible installations MUST fail explicitly. Each process owns +one session; each task MUST have at most one active headless session. + +The gateway MUST validate the runtime's protocol major/minor, real version, +required capabilities and effective limits. Incompatible major or missing +mandatory capability MUST block the session; compatible minor additions are +permitted. It MUST obey complete UTF-8 JSONL framing and separate protocol +stdout from stderr diagnostics. Invalid input/schema MUST not disappear silently. + +The runtime-owned surface covers boot/reset, set/clear normalized input, +advance, capture, state/fault, cancel and shutdown. Conflicting execution work +MUST NOT execute concurrently or be silently queued. Advance MUST preserve +requested/completed counts and stop reasons. Cancellation is observed between +frames; the current frame retains its deterministic watchdog, not a wall-clock +guest deadline. No background realtime game loop is introduced for automation. + +| Configurable, handshake-advertised limit | Default | +| --- | --- | +| Frames per advance | 600 | +| Command message | 64 KiB | +| Complete response including image/envelope | 32 MiB | +| Handshake wait | 5 s | +| Headless-call timeout | 60 s | +| Cancel/shutdown grace before process termination | 5 s | + +Oversized requests MUST fail, not be silently clamped. Responses MUST respect +their complete serialized limit. Studio MUST supervise external-process +deadlines and terminate only its owned process tree if cancellation/shutdown +does not respond within the configured grace. Report infrastructure failure +and only known progress. EOF closes the headless process; it never resumes it. + +Screenshot means the runtime's canonical **RGBA8888 framebuffer bitmap**. +Capture MUST use lossless PNG/base64 with dimensions, original stride/layout, +runtime session, `logical_frame_index` and `FrameId`. These two frame identities +MUST NOT be assumed numerically equal. Studio MUST attach build correlation. +Hashes MAY supplement but MUST NOT replace pixels. No desktop/window screenshot, +temporary-image-file transport or continuous video is permitted. + +Agent and DEV MUST receive the same capture and correlation for requested +advances. DEV MUST identify images from an older build/session as stale during +edits/rebuilds. The previous execution MUST stop before rebuilding artifacts +that it uses. Capture/build correlation MUST NOT introduce code snapshots. + +## 8. Local MCP Admission and Functional Surface + +The app MUST host Streamable HTTP at `127.0.0.1:/mcp` while +Studio is open. It MUST generate a random token per Studio start, require it +on connections, validate Origin and reject unexpected origins. No remote +binding, accounts, OAuth or stdio MCP bridge is part of this baseline. + +Copied configuration MUST contain the actual endpoint/token and MUST NOT be +written to versioned files. Instructions MUST explain that restart requires +refreshing client configuration. Copying configuration and authenticating +MUST NOT grant control. + +| Tool group | Required capabilities | Required authority | +| --- | --- | --- | +| Context/references | Project identity, languages, versions, capabilities and paginated references | Authenticated connection; no grant required | +| Control | Acquire task and release control | Prior human grant for acquisition; valid task identity for release | +| Language | Existing LSP diagnostics/navigation and supported capabilities | Valid project/task identity | +| Build | Compile and pack | Valid project/task identity | +| Headless | Boot/reset, input, advance, capture, state/fault and shutdown | Valid project/task identity | +| Operations | Query, lookup by client request identity and cancel | Valid project/task identity | + +MCP capture responses MUST expose image content plus structured metadata; +clients MUST NOT need to parse logs or fetch a temporary file to obtain pixels. +Generic shell, generic file editing, Git, publication and out-of-project changes +MUST NOT be exposed as shortcuts around these specialized services. Studio +grant does not override the external client's own permission policy or require +a new human confirmation for every authorized Studio operation. + +## 9. Project Language Context and References + +The project manifest MUST be authoritative for primary language and dependencies; +there is no parallel AI-only language configuration. PBS is the project-creation +default, not a fallback for an unknown declared language. Installed compiler/LSP +integrations MUST advertise their actual capabilities; unknown versions or +capabilities MUST be reported as unknown, not invented. + +Context MUST include: + +- explicit project identity/root; +- language list and primary designation, with separately identified known language/compiler/SDK versions; +- source extensions/scope and actual LSP/build capabilities; +- references, examples, libraries and editable versus read-only roots. + +A one-entry PBS list is valid; extensibility does not require another language +or a multilingual compiler. LSP MUST use the existing project server and support +project/library navigation through the diagnostics, definitions, references, +symbols and other queries/refactorings it actually supports. It MUST NOT +advertise nonexistent features or apply edits outside authorized scope. + +The matching language/SDK distribution MUST ship indexed local quickstart, +syntax, semantics, examples and SDK reference material. Consultation MUST work +without Studio/compiler checkouts. MCP MUST read references by identifier with +pagination, not arbitrary paths. Documentation ownership remains with its +language/SDK/library owner; packaging does not create parallel language semantics. + +Connection guidance MUST describe: connect → consult current project/languages/ +references → acquire after human grant → work using saved files and validate +through LSP/build → release. The agent need not know PBS in advance. Missing +documentation or unsupported language MUST appear as explicit limitations; +static copied instructions MUST NOT substitute for current project context. + +## 10. Delivery Phases and Conformance Gates + +The accepted slicing is runtime → DEV/shared services → MCP → integration. +No intermediate phase constitutes complete delivery of this specification. + +| Phase / plan steps | Required gate and limit | +| --- | --- | +| Runtime, 01–07 | Independent process client proves external contract, deterministic execution, canonical pixels, limits/failures and installed CLI; no Studio/AI dependency | +| DEV/shared services, 08–14 | Neutral authority/operations and document handoff first, then DEV; test grant/reclaim, Debug exclusion, dirty buffers, revocation/closure, late calls and FX lifecycle; desktop navigation smoke; doubles only in tests, no fake product endpoint | +| MCP, 15–21 | Automated MCP client proves authenticated discovery, real configuration, unauthorized rejection, exclusive acquisition, context/references, operations/deduplication, revocation and image contracts; no model required for this gate | +| Integration, 22–28 | Real runtime/LSP/build and an external coding client prove edit → build/pack → boot/input/advance → matching agent/DEV image → release; corrective loops and cleanup preserve manual Debug | + +Cross-phase conformance MUST prove API/Core neutrality, the unchanged Modulith +dependency graph, application startup/shutdown, installed/offline references, +packaging and desktop behavior. Real-client tool/image compatibility MUST be +verified with the selected client, not promised uniformly across providers. +The vertical slice MAY use a simple existing PBS program; a complete game or +mature gameplay library is not a prerequisite. + +### Decision Traceability + +| Accepted requirement | Normative location | +| --- | --- | +| D1 architecture | Section 1 and spec 9 | +| D2 runtime; B1–B3 entry/wire/order | Sections 6–7 and runtime-owned protocol | +| D3 capture; B4 capture/limits | Sections 5 and 7 | +| D4 DEV/authority | Sections 2–5; shell spec and state-restoration exclusions | +| D5 files/LSP/write scope | Sections 3 and 9 | +| D6 MCP/operations; B5–B7 | Sections 6 and 8; spec 9's HTTP exception | +| D7 languages/onboarding; B8–B9 | Sections 8–9 | +| Ordered slicing and acceptance | Section 10 | +| Accepted exclusions | Section 11 | + +## 11. Non-Goals + +- Embedded agent, chat, provider adapter, provider credentials or cost/budget accounting. +- Mirroring external conversation, reasoning or all filesystem activity. +- Pixel-art generation, full-game libraries, audio capture or deep guest introspection. +- Shared editing, isolated worktrees, code snapshots/journals/checkpoints, merge/apply, divergence recovery, undo/rollback or automatic commits/clean-tree gates. +- Replacing compiler, Packer, LSP, VM or human Debug semantics; a new general-purpose Studio source editor. +- Remote MCP, accounts/OAuth, stdio MCP bridge, network runtime discovery or provider-specific connection wizard. +- Additional language implementation, persistent operation recovery or automatic task resumption. +- Integrated discussion-framework agendas/decisions/plans in the product; those are future work, not this runtime/DEV/MCP contract. + +## Exit Criteria + +Implementation is conformant only when all phase gates hold and: + +1. Human grant, task acquisition, operation outcome and authority return are distinct and tested. +2. Service-level guards prevent conflicting manual work from grant through cleanup without blocking read-only navigation globally. +3. Save failure prevents grant; successful return refreshes documents without overwriting agent edits. +4. Revoke invalidates old calls first, works while waiting and preserves edits; project/application closure cleans owned processes and never restores authority. +5. DEV and the agent see the same canonical image with explicit build/session/frame correlation and stale labeling. +6. Local transport authentication does not bypass project/task authorization or scope restrictions. +7. Lost operation responses cannot duplicate execution; runtime crash cannot trigger replay or implicit authority release. +8. Language context and indexed local references reflect real installed support and work without source checkouts. +9. Manual Debug, architecture boundaries, packaging and real-client integration pass their regression gates. diff --git a/docs/specs/studio/8. Project-Local Studio State Specification.md b/docs/specs/studio/8. Project-Local Studio State Specification.md index db6d3f2a..df5125dc 100644 --- a/docs/specs/studio/8. Project-Local Studio State Specification.md +++ b/docs/specs/studio/8. Project-Local Studio State Specification.md @@ -79,6 +79,8 @@ The main session-restoration store MUST NOT include: - heavy operational output; - recomputable results that do not represent session restoration state. +Under DEC-0060, automation grants, task/control identities, active runtime sessions and the task-local operation/deduplication registry MUST NOT be persisted or restored through `.studio/state.json` or `.studio/setup.json`. Reopening a project MUST start under manual control. Restoring DEV as the selected workspace is presentation restoration, not permission to resume work. MCP connection credentials MUST NOT be stored in versioned files; they are regenerated on Studio restart. See the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md). + `Project-local activity` and project-local setup may still live under `.studio/`, but they are separate persistence concerns and not part of the main session-restoration store defined here. ## Ownership Rules diff --git a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md index d8a6f806..aabb8d0e 100644 --- a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md +++ b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md @@ -18,14 +18,16 @@ Define the physical and functional boundary that makes the Studio consumable by ## Authority and Precedence -This specification implements `DEC-0059` and is the normative architecture reference for the Studio split. More specific domain specs may refine behavior, but they MUST preserve the dependency direction defined here. +This specification implements `DEC-0059` and the accepted `DEC-0060` AI-first baseline. It is the normative architecture reference for the Studio split. DEC-0060 adds shared automation services and the narrowly scoped local MCP server exception below; it does not replace the module boundaries or dependency direction. + +The [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md) defines project authority, document handoff, operations, captures and delivery gates. More specific domain specs MUST preserve the dependency direction defined here. Normative requirements describe the target contract, not a claim that every delivery phase is already implemented. ## Architectural Model The Studio is a set of project and tooling services consumed by adapters: ```text -JavaFX UI ──> Studio API <── future non-visual adapters +JavaFX UI ──> Studio API <── local MCP adapter <── external coding agent │ ▼ Studio Core @@ -34,7 +36,7 @@ JavaFX UI ──> Studio API <── future non-visual adapters application/infrastructure adapters ``` -JavaFX is the current human adapter. A future agent surface is not part of this specification, but MUST be able to consume the same neutral services instead of simulating UI interaction. +JavaFX is the human adapter; DEV is its authorization and observation workspace. The local MCP adapter exposes the same neutral services to an external coding agent. Neither adapter MAY simulate the other adapter's UI or duplicate project authority, build/pack or execution orchestration. The external client owns the agent, chat, model/provider credentials and coding loop. ## Physical Modules @@ -53,7 +55,8 @@ The public Studio API MUST be plain Java and MUST NOT depend on: - JavaFX; - Spring Framework, Spring Boot, or Spring Modulith; -- AI, MCP, or provider SDKs; +- HTTP, AI, MCP, or provider SDKs; +- concrete runtime-wire or MCP transport DTOs; - concrete compiler, Packer, LSP, or runtime implementations; - `p.studio.core` or `p.studio.ui.javafx` internals. @@ -68,6 +71,7 @@ Core classes MUST be POJOs with constructor injection and MUST remain testable w The core module MUST NOT: - depend on JavaFX or UI packages; +- depend on HTTP/MCP SDKs, Spring, or concrete external protocol DTOs; - call `Platform.runLater`; - perform navigation or workspace selection; - use presentation severity or visual state as domain semantics; @@ -76,11 +80,11 @@ The core module MUST NOT: The functional core modules are: - `project`: project identity, catalog, creation, paths, setup, and restoration state; -- `session`: open-project lifecycle, ordered cleanup, execution ownership, and the LSP lifecycle port; +- `session`: open-project lifecycle, project-scoped automation authority, document handoff, ordered cleanup, execution ownership, and the LSP lifecycle port; - `assets`: Studio-owned asset projections, metadata, policies, non-visual sessions, validation, and workflow orchestration; - `shipper`: build/pack coordination, manifest generation, artifacts, and neutral logs/results; -- `runtime`: runtime settings, handshake, process/client lifecycle, and technical logs; -- `execution`: play/stop state, cancellation, shutdown, and orchestration of shipper and runtime. +- `runtime`: runtime settings, handshake, process/client lifecycle, canonical capture contracts, and technical logs; human Debug and headless automation retain distinct protocol/lifecycle boundaries; +- `execution`: play/stop and automation operation state, cancellation, shutdown, and orchestration of shipper and runtime. The functional dependency direction MUST remain: @@ -92,6 +96,10 @@ execution --> project, shipper, runtime session --> project, execution, LSP port ``` +Session-owned authority lifetime MUST NOT introduce reverse functional dependencies from `assets`, `shipper`, `runtime` or `execution` to the concrete `session` module. Service entry points MUST receive the shared authority through neutral contracts and composition, not reach into JavaFX or concrete session implementations. Document-handoff participants likewise use neutral contracts; their presentation buffers remain adapter-owned. + +Manual Debug and project mutation MUST enforce the same project authority as automation. Disabled UI buttons alone are not authorization. Grant, acquisition, operation completion and authority return MUST remain distinct lifecycle facts. + ## JavaFX Adapter Rules The JavaFX module MUST depend on Studio API contracts rather than core or provider implementations. It owns visual state, UI events, navigation, FX-thread transitions, CSS, fonts, locale bindings, and lifecycle of visual objects. @@ -104,7 +112,11 @@ The JavaFX module MUST NOT directly invoke compiler implementations, `p.packer`, ## Spring Composition -Spring Boot MUST be used only by `prometeu-app` as a non-web composition and lifecycle mechanism. The application MUST start with `WebApplicationType.NONE` or an equivalent guarantee and MUST NOT introduce Spring Web, WebFlux, Data, AI, durable events, or a web server without a later accepted decision. +Spring Boot MUST be used only by `prometeu-app` for desktop composition and lifecycle. `WebApplicationType.NONE` remains a valid composition mode with an explicitly managed local HTTP adapter. Conformance MUST NOT impose an unconditional absence of a web server that would forbid the DEC-0060 MCP exception. + +The sole accepted HTTP-server use is an in-process MCP Streamable HTTP endpoint at `127.0.0.1:/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a random per-Studio-start token, validate Origin and reject unexpected origins, and stop with Studio. Connection authentication MUST NOT grant project/task authority. The token MUST NOT be stored in versioned files, and restart requires refreshed client configuration. + +This exception does not authorize a web UI, remote binding, general-purpose web application, accounts, OAuth, or a stdio MCP bridge. HTTP/MCP dependencies MUST NOT enter API/Core or the JavaFX adapter. Spring Data, Spring AI and durable event infrastructure remain outside the accepted architecture. Spring configuration MAY create core services, infrastructure adapters, and a JavaFX composition factory. It MUST NOT use field injection, context lookup, broad service bags, or a replacement static container. @@ -125,6 +137,9 @@ A narrow consumer-owned gateway MUST be used when the available integration is c | `session` | LSP | Neutral session-owned lifecycle port | | `runtime` | external runtime/process | Narrow runtime-owned gateway | | JavaFX UI | Studio | Studio API only | +| MCP adapter | Studio | Studio API only; transport DTO translation belongs to infrastructure | + +The headless gateway MUST start `prometeu headless --stdio` from the configured runtime installation and map the runtime-owned JSONL contract to neutral results. It MUST NOT reuse the human DevTools connection, introduce a native Rust/Java binding, search/download another runtime, or redefine firmware/VM semantics. Runtime process supervision and the existing project LSP client belong to application/infrastructure adapters, not UI controls. `p.packer` remains an autonomous domain and MUST NOT depend on any `p.studio` package. Studio MUST NOT copy or assume ownership of Packer semantics. @@ -138,21 +153,27 @@ Long-running build, pack, runtime, and execution work MUST expose a neutral oper Core services MUST submit such work through the neutral `OperationExecutor` port. `prometeu-app` owns the executor-backed implementation and its thread lifecycle; JavaFX consumes `OperationHandle` completion and snapshots and performs only the required FX-thread projection. +Automation MUST reuse this operation boundary. Task authority is separate from operation success, guest fault, infrastructure failure or cancellation. Revocation MUST invalidate task authority before stopping managed work, refreshing open documents and releasing manual control. Closing the project or application MUST perform that cleanup; changing the active workspace MUST NOT. + +Build and advance admission MUST return a promptly queryable operation identity. Task-scoped, in-memory `clientRequestId` deduplication MUST live behind the shared services, not in a second MCP orchestrator. Runtime `requestId` is wire correlation and MUST NOT be treated as that deduplication mechanism. Late calls/results MUST NOT restore revoked authority. + ## Conformance Gates The architecture is conformant only when all of the following hold together: -- API and core compile without JavaFX or Spring dependencies; +- API and core compile without JavaFX, Spring, HTTP/MCP SDKs or concrete transport DTO dependencies; - UI has no dependency on core or concrete external providers; - `ApplicationModules.verify()` succeeds for the exclusive `p.studio.core` root; -- the application boots and shuts down in non-web mode; +- the desktop application boots and shuts down with no web exposure other than the authorized loopback MCP endpoint, whose transport is lifecycle-managed by the app; +- MCP and JavaFX consume shared authorization and operations; grant/Debug exclusion and cleanup are enforced in services; - `Container`, `AppContainer`, compatibility allowlists, and the mixed module are absent; - unit, integration, architecture, packaging, and desktop smoke tests pass; - no service locator or context lookup replaces the removed static container. ## Non-Goals -- creating an agent or MCP module; +- embedding an agent, chat or provider adapter; +- adding a second orchestration/authorization implementation inside MCP; - replacing JavaFX with a web UI; - migrating the Studio to Rust, Electron, Tauri, or a parallel rewrite; - redesigning compiler, Packer, LSP, or runtime semantics; diff --git a/docs/specs/studio/README.md b/docs/specs/studio/README.md index d3b02240..1d8ad82b 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -56,6 +56,7 @@ The current Studio core corpus is: 4. [`4. Assets Workspace Specification.md`](4.%20Assets%20Workspace%20Specification.md) 5. [`8. Project-Local Studio State Specification.md`](8.%20Project-Local%20Studio%20State%20Specification.md) 6. [`9. Studio Core and Adapter Architecture Specification.md`](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md) +7. [`10. DEV and Automation Specification.md`](10.%20DEV%20and%20Automation%20Specification.md) ## Reading Order @@ -66,7 +67,8 @@ Recommended order: 3. components module policy; 4. assets workspace behavior; 5. project-local Studio state behavior; -6. Studio Core, adapter, composition, and external integration boundaries. +6. Studio Core, adapter, composition, and external integration boundaries; +7. DEV authority, document handoff, automation operations/captures and phased integration gates. ## Current Wave Notes @@ -74,9 +76,9 @@ The embedded Studio code-editor stack was removed by `DEC-0031`. Normative reminders: -- the active Studio workspace corpus is `Assets`, `Debug`, and `Shipper`; +- the accepted Studio workspace corpus is `Assets`, `Debug`, `Shipper`, and `DEV`; the DEV implementation follows DEC-0060's phased delivery; - project-local Studio session state remains normative and is owned by `StudioProjectSession`; -- any future external-editor backend or replacement language-service architecture requires a new accepted decision before new Studio specs are introduced. -- the Studio backend is exposed through neutral API contracts shared by the JavaFX adapter and future non-visual adapters; -- Spring Boot is a non-web composition root, while Spring Modulith verifies the JavaFX-free `p.studio.core` boundary; +- DEC-0060 authorizes an external coding agent using native file tools and the existing project LSP through MCP; it does not reinstate the embedded editor or authorize a replacement language-service architecture; +- the Studio backend is exposed through neutral API contracts shared by JavaFX and the local MCP adapter, without duplicated authority or orchestration; +- Spring Boot remains the desktop composition root with the narrow DEC-0060 local MCP HTTP exception; Spring Modulith still verifies the JavaFX-free `p.studio.core` boundary; - `p.studio.Container`, `AppContainer`, and the mixed `prometeu-studio` module are not valid final architecture. diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 56dde4e9..1c17f60e 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -28,3 +28,15 @@ javafx { version = libs.versions.javafx.get() modules("javafx.controls", "javafx.fxml") } + +// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. +tasks.named("test") { exclude("**/DevDesktopTest.class") } +tasks.register("devDesktopTest") { + group = "verification" + description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/DevDesktopTest.class") + systemProperty("java.awt.headless", "false") +} 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 ccf134b8..36a39a5a 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -101,18 +101,18 @@ public class StudioApplicationConfiguration { } @Bean - AssetCatalog assetCatalog(PackerWorkspaceService packer) { - return new PackerAssetCatalog(packer); + AssetCatalog assetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + return new PackerAssetCatalog(packer, access); } @Bean - AssetCommands assetCommands(PackerWorkspaceService packer) { - return new PackerAssetCommands(packer); + AssetCommands assetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + return new PackerAssetCommands(packer, access); } @Bean - AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations) { - return new PackerAssetPacking(packer, operations); + AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + return new PackerAssetPacking(packer, operations, access); } @Bean @@ -126,8 +126,8 @@ public class StudioApplicationConfiguration { } @Bean - AssetWorkspaceStorage assetWorkspaceStorage() { - return new FileSystemAssetWorkspaceStorage(); + AssetWorkspaceStorage assetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) { + return new FileSystemAssetWorkspaceStorage(access); } @Bean @@ -146,18 +146,18 @@ public class StudioApplicationConfiguration { } @Bean - AssetMetadataService assetMetadataService(ObjectMapper mapper) { - return new AssetStudioMetadataService(mapper); + AssetMetadataService assetMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + return new AssetStudioMetadataService(mapper, access); } @Bean - SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper) { - return new SceneBankWorkflowService(assetCatalog, mapper); + SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + return new SceneBankWorkflowService(assetCatalog, mapper, access); } @Bean - TiledAssetService tiledAssetService(AssetMetadataService metadataService) { - return new TiledAssetGenerationService(metadataService); + TiledAssetService tiledAssetService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) { + return new TiledAssetGenerationService(metadataService, access); } @Bean @@ -177,8 +177,8 @@ public class StudioApplicationConfiguration { @Bean Shipper shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, - OperationExecutor operations) { - return new StudioShipperService(compiler, packer, mapper, operations); + OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + return new StudioShipperService(compiler, packer, mapper, operations, access); } @Bean(destroyMethod = "shutdown") @@ -198,8 +198,8 @@ public class StudioApplicationConfiguration { @Bean ExecutionControllerFactory executionControllerFactory(Shipper shipper, RuntimeGateway runtime, - OperationExecutor operations) { - return new DefaultExecutionControllerFactory(shipper, runtime, operations); + OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + return new DefaultExecutionControllerFactory(shipper, runtime, operations, access); } @Bean @@ -222,10 +222,16 @@ public class StudioApplicationConfiguration { return new LspLifecycleAdapter(lifecycle); } + @Bean + p.studio.core.project.ProjectAccessRegistry projectAccessRegistry() { + return new p.studio.core.project.ProjectAccessRegistry(); + } + @Bean ProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore, - ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) { - return new DefaultProjectSessionFactory(stateStore, setupStore, lsp); + ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, + p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) { + return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations); } @Bean diff --git a/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java b/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java index b128c030..65f3b5ef 100644 --- a/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java +++ b/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java @@ -39,6 +39,9 @@ public final class ExecutorOperationExecutor implements OperationExecutor { private final String summary; private final Callable operation; private final CompletableFuture completion = new CompletableFuture<>(); + private final CompletableFuture termination = new CompletableFuture<>(); + private final Object workerLifecycle = new Object(); + private boolean started; private final CopyOnWriteArrayList> subscribers = new CopyOnWriteArrayList<>(); private final AtomicReference snapshot; private volatile Future task; @@ -62,12 +65,19 @@ public final class ExecutorOperationExecutor implements OperationExecutor { } } return null; - }); + }) { + @Override public void run() { + synchronized (workerLifecycle) { started = true; } + try { super.run(); } + finally { termination.complete(null); } + } + }; task = submitted; try { transition(OperationState.RUNNING, summary); executor.execute(submitted); } catch (RuntimeException failure) { + termination.complete(null); if (transitionTerminal(OperationState.FAILED, failureSummary(failure))) { completion.completeExceptionally(failure); } @@ -89,6 +99,8 @@ public final class ExecutorOperationExecutor implements OperationExecutor { return completion; } + @Override public CompletionStage termination() { return termination; } + @Override public boolean cancel() { while (true) { @@ -99,8 +111,9 @@ public final class ExecutorOperationExecutor implements OperationExecutor { final OperationSnapshot cancelled = new OperationSnapshot(id, OperationState.CANCELLED, Instant.now(), summary); if (snapshot.compareAndSet(current, cancelled)) { final Future submitted = task; - if (submitted != null) { - submitted.cancel(true); + synchronized (workerLifecycle) { + if (submitted != null) submitted.cancel(true); + if (!started) termination.complete(null); } completion.cancel(false); publish(cancelled); diff --git a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java new file mode 100644 index 00000000..a44980ea --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java @@ -0,0 +1,146 @@ +package p.studio.app; + +import javafx.application.Platform; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.api.operation.OperationSubscription; +import p.studio.api.project.*; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.core.execution.DefaultExecutionSession; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.ui.javafx.controls.forms.*; +import p.studio.ui.javafx.events.StudioEventBus; +import p.studio.ui.javafx.utilities.i18n.I18nService; +import p.studio.ui.javafx.workspaces.*; +import p.studio.ui.javafx.workspaces.debug.DebugWorkspace; +import p.studio.ui.javafx.workspaces.dev.*; +import java.nio.file.*; +import java.util.List; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; + +/** Uses the actual desktop toolkit; runtime, operation and document inputs are test consumers only. */ +class DevDesktopTest { + @TempDir Path root; + @BeforeAll static void toolkit() throws Exception { + var ready = new CompletableFuture(); + Platform.startup(() -> { Platform.setImplicitExit(false); ready.complete(null); }); + ready.get(10, TimeUnit.SECONDS); + } + @AfterAll static void stopToolkit() { Platform.exit(); } + static void fx(Runnable work) throws Exception { + var completed = new CompletableFuture(); + Platform.runLater(() -> { try { work.run(); completed.complete(null); } catch (Throwable failure) { completed.completeExceptionally(failure); } }); + completed.get(10, TimeUnit.SECONDS); + } + + @Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception { + var pool = Executors.newSingleThreadExecutor(); + var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); + var subscriptions = new AtomicInteger(); + var observed = (AutomationSession) java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(), + new Class[]{AutomationSession.class}, (proxy, method, args) -> { + var result = method.invoke(authority, args); + if (method.getName().equals("subscribe")) { + subscriptions.incrementAndGet(); + return (OperationSubscription) () -> { ((OperationSubscription) result).unsubscribe(); subscriptions.decrementAndGet(); }; + } + return result; + }); + var stage = new Stage[1]; var host = new WorkspaceHost[1]; var dev = new DevWorkspace[1]; + var locale = new I18nService(); + try { + fx(() -> { + var project = new ProjectReference("DEV smoke", "1", "pbs", 1, ProjectTarget.Game, root); + var events = new StudioEventBus(); + host[0] = new WorkspaceHost(); + dev[0] = new DevWorkspace(project, observed, locale, events); + host[0].register(dev[0]); + host[0].register(new DebugWorkspace(project, new DefaultExecutionSession(), locale, events)); + stage[0] = new Stage(); stage[0].setTitle("DEV/Debug desktop verification"); + stage[0].setScene(new Scene(host[0], 1050, 800)); stage[0].show(); host[0].change(WorkspaceId.DEV); + }); + fx(() -> { + assertEquals(1, subscriptions.get()); + assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled()); + ((Button) dev[0].rootNode().lookup("#dev-grant")).fire(); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get()); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + host[0].change(WorkspaceId.DEV); + }); + fx(() -> assertEquals(1, subscriptions.get())); + var task = authority.acquire(); // Intentionally outside the FX thread. + authority.attachRuntime(task.task(), new ManagedHeadlessSession() { + public String sessionId() { return "smoke-session"; } + public void cancel() { } + public CompletionStage shutdown() { return CompletableFuture.completedFuture(null); } + }); + // Real 1x1 PNG, supplied by the test runtime. Product never fabricates captures. + var png = java.util.Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9l0AAAAASUVORK5CYII="); + authority.submit(task.task(), "capture", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 4, 4, List.of(), + new CanonicalCapture("smoke-session", "smoke-build", 4, 1, 1, 1, 1, png))).termination().toCompletableFuture().get(5, TimeUnit.SECONDS); + fx(() -> { + assertTrue(((Button) dev[0].rootNode().lookup("#dev-grant")).isDisabled()); + assertTrue(dev[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label) + .map(n -> ((Label) n).getText()).anyMatch(t -> t.contains("logical=4") && t.contains("FrameId=1"))); + ((Button) dev[0].rootNode().lookup("#dev-reclaim")).fire(); + assertEquals(ControlState.MANUAL, authority.snapshot().state()); + assertTrue(authority.snapshot().stale()); + locale.setLocale(java.util.Locale.forLanguageTag("pt-BR")); + host[0].deactivateCurrentWorkspace(); assertEquals(0, subscriptions.get()); + authority.grant(false); locale.setLocale(java.util.Locale.ENGLISH); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + }); + } finally { + fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); }); + authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow(); + } + } + + @Test void formsSaveFailurePreservesDraftAndReturnReadsExternalContent() throws Exception { + var file = root.resolve("document.txt"); Files.writeString(file, "initial"); + fx(() -> { + var form = new TestForm(); form.draft = "edited"; form.dirty = true; + form.fail = true; + assertThrows(CompletionException.class, () -> form.saveForHandoff().toCompletableFuture().join()); + assertTrue(form.hasUnsavedDraft()); assertEquals("edited", form.draft); + form.fail = false; form.saveForHandoff().toCompletableFuture().join(); assertFalse(form.hasUnsavedDraft()); + form.draft = "stale presentation"; + try { Files.writeString(file, "external agent edit"); } catch (Exception failure) { throw new RuntimeException(failure); } + form.discardDraftForHandoff(); + try { form.draft = Files.readString(file); } catch (Exception failure) { throw new RuntimeException(failure); } + assertEquals("external agent edit", form.draft); + }); + } + + @Test void lockedUiBlocksMutationActionsButNotReadOnlyActions() throws Exception { + fx(() -> { + var root = new VBox(); var mutate = new Button("write"); var inspect = new Button("inspect"); + inspect.getProperties().put(ManualProjectUiGuard.READ_ONLY_ACTION, true); + var writes = new AtomicInteger(); var reads = new AtomicInteger(); + mutate.setOnAction(e -> writes.incrementAndGet()); inspect.setOnAction(e -> reads.incrementAndGet()); + root.getChildren().addAll(mutate, inspect); ManualProjectUiGuard.install(root, () -> false); + mutate.fire(); inspect.fire(); assertEquals(0, writes.get()); assertEquals(1, reads.get()); + }); + } + static class TestForm extends StudioFormSection { + boolean dirty, fail; String draft = ""; + TestForm() { super(new I18nService()); } + protected String formSectionId() { return "test"; } + protected String sectionTitle() { return "test"; } + protected StudioFormMode formMode() { return StudioFormMode.EDITING; } + protected boolean isDirty() { return dirty; } + protected void renderSection() { } + protected void beginEdit() { } + protected void apply() { if (!fail) dirty = false; finishHandoffSave(!fail, "save failure"); } + protected void reset() { } + protected void cancel() { dirty = false; draft = ""; } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java b/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java index 61ad1075..bf1cfa26 100644 --- a/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java +++ b/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java @@ -12,6 +12,39 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; final class ExecutorOperationExecutorTest { + @Test + void cancellationDoesNotPretendAnUncooperativeWorkerHasStopped() throws Exception { + final var executor = Executors.newSingleThreadExecutor(); + final var started = new CountDownLatch(1); + final var finish = new CountDownLatch(1); + try { + var handle = new ExecutorOperationExecutor(executor).submit("stubborn worker", () -> { + started.countDown(); + boolean done = false; + while (!done) try { finish.await(); done = true; } catch (InterruptedException ignored) { } + return 42; + }); + assertTrue(started.await(2, TimeUnit.SECONDS)); + handle.cancel(); + assertTrue(handle.completion().toCompletableFuture().isCancelled()); + org.junit.jupiter.api.Assertions.assertFalse(handle.termination().toCompletableFuture().isDone()); + finish.countDown(); + handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS); + } finally { finish.countDown(); executor.shutdownNow(); } + } + + @Test + void cancellingQueuedWorkCompletesTerminationWithoutRunningItsBody() throws Exception { + final var executor = Executors.newSingleThreadExecutor(); + final var finish = new CountDownLatch(1); + try { + executor.submit(() -> { try { finish.await(); } catch (InterruptedException ignored) { } }); + var handle = new ExecutorOperationExecutor(executor).submit("queued", () -> { throw new AssertionError("must not execute"); }); + handle.cancel(); + handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS); + } finally { finish.countDown(); executor.shutdownNow(); } + } + @Test void completesWithTypedResultAndTerminalSnapshot() throws Exception { final var executor = Executors.newSingleThreadExecutor(); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java new file mode 100644 index 00000000..099ac920 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java @@ -0,0 +1,7 @@ +package p.studio.api.automation; +import java.util.List; +public record AutomationOutcome(Kind kind, long requestedFrames, long completedFrames, + List diagnostics, CanonicalCapture capture) { + public enum Kind { SUCCEEDED, TERMINATED, GUEST_FAULT, INFRASTRUCTURE_FAILURE, CANCELLED } + public AutomationOutcome { diagnostics = List.copyOf(diagnostics); } +} 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 new file mode 100644 index 00000000..dc46493b --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java @@ -0,0 +1,20 @@ +package p.studio.api.automation; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletionStage; +import java.util.function.Consumer; +import p.studio.api.operation.OperationHandle; +import p.studio.api.operation.OperationSubscription; +public interface AutomationSession { + AutomationSnapshot snapshot(); + OperationSubscription subscribe(Consumer listener); + OperationSubscription registerDocuments(DocumentHandoff documents); + CompletionStage grant(boolean saveUnsavedDocuments); + ControlResult acquire(); + CompletionStage release(TaskIdentity task); + CompletionStage reclaim(); + CompletionStage closeAsync(); + /** 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); + void markCaptureStale(); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java new file mode 100644 index 00000000..7b3fba5b --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java @@ -0,0 +1,12 @@ +package p.studio.api.automation; +import java.nio.file.Path; +import java.util.List; +import p.studio.api.operation.OperationSnapshot; +public record AutomationSnapshot(Path projectRoot, ControlState state, boolean handoffPending, + boolean closed, int manualOperations, TaskIdentity task, OperationSnapshot operation, + CanonicalCapture capture, boolean stale, List diagnostics, List calls) { + public AutomationSnapshot { diagnostics = List.copyOf(diagnostics); calls = List.copyOf(calls); } + public boolean manualAllowed() { return !closed && !handoffPending && state == ControlState.MANUAL; } + public boolean canGrant() { return manualAllowed() && manualOperations == 0; } + public boolean canReclaim() { return !closed && state != ControlState.MANUAL; } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java new file mode 100644 index 00000000..582bdf0c --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java @@ -0,0 +1,12 @@ +package p.studio.api.automation; +import java.util.Objects; +/** Lossless PNG bytes; stride describes the original RGBA8888 buffer, not PNG padding. */ +public record CanonicalCapture(String sessionId, String buildId, long logicalFrameIndex, + long frameId, int width, int height, int stridePixels, byte[] png) { + public CanonicalCapture { + Objects.requireNonNull(sessionId); Objects.requireNonNull(buildId); Objects.requireNonNull(png); + if (width <= 0 || height <= 0 || stridePixels < width) throw new IllegalArgumentException("invalid frame layout"); + png = png.clone(); + } + @Override public byte[] png() { return png.clone(); } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java new file mode 100644 index 00000000..461dc8d8 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java @@ -0,0 +1,10 @@ +package p.studio.api.automation; +/** A typed admission failure; adapters must preserve the domain status. */ +public final class ControlDeniedException extends IllegalStateException { + private final ControlResult.Status status; + public ControlDeniedException(ControlResult.Status status) { + super("Project control: " + status); + this.status = status; + } + public ControlResult.Status status() { return status; } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java new file mode 100644 index 00000000..a8544e28 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java @@ -0,0 +1,6 @@ +package p.studio.api.automation; +public record ControlResult(Status status, TaskIdentity task, String diagnostic) { + public enum Status { GRANTED, ACQUIRED, RETURNED, BUSY, DIRTY_DOCUMENTS, SAVE_FAILED, NOT_GRANTED, INVALID_TASK, CLOSED, CLEANUP_FAILED } + public boolean success() { return status == Status.GRANTED || status == Status.ACQUIRED || status == Status.RETURNED; } + public static ControlResult of(Status status, String message) { return new ControlResult(status, null, message); } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java new file mode 100644 index 00000000..ceab85a4 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java @@ -0,0 +1,2 @@ +package p.studio.api.automation; +public enum ControlState { MANUAL, WAITING_FOR_AGENT, AGENT_WORKING, RETURNING_CONTROL } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java new file mode 100644 index 00000000..f1cd77c8 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java @@ -0,0 +1,10 @@ +package p.studio.api.automation; +import java.util.concurrent.CompletionStage; +/** A participant must complete only after saves/refreshes, not when they are scheduled. */ +public interface DocumentHandoff extends AutoCloseable { + CompletionStage hasUnsavedChanges(); + CompletionStage saveAll(); + CompletionStage refreshFromDisk(); + /** Disposes presentation work on project closure; must not write buffered content. */ + @Override default void close() { } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java new file mode 100644 index 00000000..0b8f9b71 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java @@ -0,0 +1,8 @@ +package p.studio.api.automation; +import java.util.concurrent.CompletionStage; +/** Lifecycle port implemented by the process adapter, never by JavaFX. */ +public interface ManagedHeadlessSession { + String sessionId(); + void cancel(); + CompletionStage shutdown(); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java new file mode 100644 index 00000000..437e1848 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java @@ -0,0 +1,7 @@ +package p.studio.api.automation; +/** Keeps grant admission closed until the actual manual work has finished. */ +@FunctionalInterface +public interface ManualLease extends AutoCloseable { + @Override void close(); + default void onProjectClose(Runnable cancellation) { } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java new file mode 100644 index 00000000..56b1a63b --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java @@ -0,0 +1,17 @@ +package p.studio.api.automation; +import java.nio.file.Path; +/** Shared service guard. Paths may be project roots or contained asset paths. */ +public interface ProjectAccess { + ManualLease enterManual(Path path); + + default p.studio.api.operation.OperationHandle submitManual(Path path, + p.studio.api.operation.OperationExecutor executor, String summary, java.util.concurrent.Callable work) { + ManualLease lease = enterManual(path); + try { + var operation = executor.submit(summary, work); + lease.onProjectClose(operation::cancel); + operation.termination().whenComplete((result, failure) -> lease.close()); + return operation; + } catch (RuntimeException failure) { lease.close(); throw failure; } + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java new file mode 100644 index 00000000..d4084cc3 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java @@ -0,0 +1,9 @@ +package p.studio.api.automation; +import java.nio.file.Path; +import java.util.Objects; +public record TaskIdentity(Path projectRoot, String value) { + public TaskIdentity { + projectRoot = Objects.requireNonNull(projectRoot).toAbsolutePath().normalize(); + if (Objects.requireNonNull(value).isBlank()) throw new IllegalArgumentException("empty task identity"); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java b/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java index 56edd2c3..fc5bd03f 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java @@ -10,6 +10,11 @@ public interface OperationHandle { CompletionStage completion(); + /** Completes only when the worker has stopped, even if cancellation was acknowledged earlier. */ + default CompletionStage termination() { + return completion().handle((result, failure) -> null); + } + boolean cancel(); OperationSubscription subscribe(Consumer subscriber); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java b/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java index 6210746e..687ae501 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java @@ -14,6 +14,8 @@ public interface ProjectSession extends AutoCloseable { ExecutionSession executionSession(); + p.studio.api.automation.AutomationSession automation(); + void replaceProjectLocalStudioState(ProjectLocalStudioState state); void saveProjectLocalStudioState(); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java index c7c13cff..afdeb4e7 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java @@ -10,6 +10,13 @@ import java.nio.file.Path; import java.util.Objects; public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStorage { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public FileSystemAssetWorkspaceStorage() { } + public FileSystemAssetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) { + this(); + this.access = java.util.Objects.requireNonNull(access); + } + @Override public Path assetsRoot(ProjectReference projectReference) { return Objects.requireNonNull(projectReference, "projectReference") @@ -21,12 +28,14 @@ public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStor @Override public AssetWorkspacePreparation prepare(ProjectReference projectReference) { - final Path root = assetsRoot(projectReference); - try { - Files.createDirectories(root); - return new AssetWorkspacePreparation(true, root, ""); - } catch (IOException exception) { - return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory.")); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(projectReference.rootPath())) { + final Path root = assetsRoot(projectReference); + try { + Files.createDirectories(root); + return new AssetWorkspacePreparation(true, root, ""); + } catch (IOException exception) { + return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory.")); + } } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java index 4345f9c1..dc9ff473 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java @@ -14,6 +14,12 @@ import java.util.List; import java.util.Objects; public final class PackerAssetCatalog implements AssetCatalog { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public PackerAssetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + this(packer); + this.access = java.util.Objects.requireNonNull(access); + } + private final PackerWorkspaceService packer; public PackerAssetCatalog(PackerWorkspaceService packer) { @@ -22,20 +28,22 @@ public final class PackerAssetCatalog implements AssetCatalog { @Override public List list(ProjectReference projectReference, boolean deepSync) { - final var context = new p.packer.messages.PackerProjectContext( - projectReference.name(), - projectReference.rootPath()); - return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream() - .map(summary -> new AssetSummary( - AssetReference.of(summary.assetReference().value()), - summary.identity().assetName(), - AssetRegistrationState.valueOf(summary.state().name()), - AssetBuildParticipation.valueOf(summary.buildParticipation().name()), - summary.identity().assetId(), - AssetFamily.valueOf(summary.assetFamily().name()), - summary.identity().assetRoot(), - summary.preloadEnabled(), - summary.hasDiagnostics())) - .toList(); + try (p.studio.api.automation.ManualLease accessLease = deepSync ? access.enterManual(projectReference.rootPath()) : () -> {}) { + final var context = new p.packer.messages.PackerProjectContext( + projectReference.name(), + projectReference.rootPath()); + return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream() + .map(summary -> new AssetSummary( + AssetReference.of(summary.assetReference().value()), + summary.identity().assetName(), + AssetRegistrationState.valueOf(summary.state().name()), + AssetBuildParticipation.valueOf(summary.buildParticipation().name()), + summary.identity().assetId(), + AssetFamily.valueOf(summary.assetFamily().name()), + summary.identity().assetRoot(), + summary.preloadEnabled(), + summary.hasDiagnostics())) + .toList(); + } } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java index a79552cc..1e629840 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java @@ -14,6 +14,12 @@ import java.util.Map; import java.util.Objects; public final class PackerAssetCommands implements AssetCommands { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public PackerAssetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + this(packer); + this.access = java.util.Objects.requireNonNull(access); + } + private final PackerWorkspaceService packer; public PackerAssetCommands(PackerWorkspaceService packer) { @@ -23,64 +29,80 @@ public final class PackerAssetCommands implements AssetCommands { @Override public AssetMutationResult create(ProjectReference project, String assetRoot, String assetName, AssetFamily assetFamily, String outputFormat, String outputCodec, boolean preloadEnabled) { - final var result = packer.createAsset(new CreateAssetRequest( - context(project), assetRoot, assetName, - AssetFamilyCatalog.valueOf(assetFamily.name()), - OutputFormatCatalog.valueOf(outputFormat), - OutputCodecCatalog.valueOf(outputCodec), - preloadEnabled)); - return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.createAsset(new CreateAssetRequest( + context(project), assetRoot, assetName, + AssetFamilyCatalog.valueOf(assetFamily.name()), + OutputFormatCatalog.valueOf(outputFormat), + OutputCodecCatalog.valueOf(outputCodec), + preloadEnabled)); + return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult move(ProjectReference project, AssetReference assetReference, String targetRoot) { - final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot)); - return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot)); + return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult register(ProjectReference project, AssetReference assetReference) { - final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference))); - return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference))); + return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult delete(ProjectReference project, AssetReference assetReference) { - final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference))); - return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference))); + return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult updateBuildParticipation(ProjectReference project, AssetReference assetReference, boolean includeInBuild) { - final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest( - context(project), reference(assetReference), includeInBuild)); - return mutation(result.status(), result.summary(), result.assetReference(), null, null); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest( + context(project), reference(assetReference), includeInBuild)); + return mutation(result.status(), result.summary(), result.assetReference(), null, null); + } } @Override public AssetUpdateResult updateContract(ProjectReference project, AssetReference assetReference, boolean preload, String outputCodec, Map codecFieldValues, Map metadataFieldValues) { - final var result = packer.updateAssetContract(new UpdateAssetContractRequest( - context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec), - codecFieldValues, metadataFieldValues)); - return new AssetUpdateResult(result.success(), result.errorMessage()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.updateAssetContract(new UpdateAssetContractRequest( + context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec), + codecFieldValues, metadataFieldValues)); + return new AssetUpdateResult(result.success(), result.errorMessage()); + } } @Override public AssetUpdateResult applyBankComposition(ProjectReference project, AssetReference assetReference, List selectedPaths) { - final var result = packer.applyBankComposition(new ApplyBankCompositionRequest( - context(project), reference(assetReference), selectedPaths)); - return new AssetUpdateResult(result.success(), result.errorMessage()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.applyBankComposition(new ApplyBankCompositionRequest( + context(project), reference(assetReference), selectedPaths)); + return new AssetUpdateResult(result.success(), result.errorMessage()); + } } @Override public AssetUpdateResult applyPaletteOverhauling(ProjectReference project, AssetReference assetReference, List> selectedPalettes) { - final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest( - context(project), reference(assetReference), selectedPalettes)); - return new AssetUpdateResult(result.success(), result.errorMessage()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest( + context(project), reference(assetReference), selectedPalettes)); + return new AssetUpdateResult(result.success(), result.errorMessage()); + } } private static PackerProjectContext context(ProjectReference project) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java index f9918794..58a45740 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java @@ -10,6 +10,12 @@ import p.studio.api.operation.OperationHandle; import java.util.Objects; public final class PackerAssetPacking implements AssetPacking { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public PackerAssetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + this(packer, operations); + this.access = java.util.Objects.requireNonNull(access); + } + private final PackerWorkspaceService packer; private final OperationExecutor operations; @@ -20,7 +26,7 @@ public final class PackerAssetPacking implements AssetPacking { @Override public OperationHandle deepSync(ProjectReference project) { - return operations.submit("Synchronize project assets", () -> deepSyncNow(project)); + return access.submitManual(project.rootPath(), operations, "Synchronize project assets", () -> deepSyncNow(project)); } private AssetSyncResult deepSyncNow(ProjectReference project) { @@ -63,7 +69,7 @@ public final class PackerAssetPacking implements AssetPacking { @Override public OperationHandle pack(ProjectReference project) { - return operations.submit("Pack project assets", () -> packNow(project)); + return access.submitManual(project.rootPath(), operations, "Pack project assets", () -> packNow(project)); } private AssetPackExecution packNow(ProjectReference project) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java index 421f98c1..3f736e47 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java @@ -18,6 +18,12 @@ import java.util.Objects; import java.util.Set; public final class AssetStudioMetadataService implements AssetMetadataService { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public AssetStudioMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + this(mapper); + this.access = java.util.Objects.requireNonNull(access); + } + public static final String STUDIO_ASSET_METADATA_FILE = "studio.asset.json"; public static final String SCENE_BANK_SUPPORT_FILE = "scene-bank.studio.json"; public static final String GLYPH_MATERIAL_SUPPORT_FILE = "glyph-material.json"; @@ -43,11 +49,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService { @Override public AssetMetadataWriteResult writeSceneBankMetadata(Path assetRoot, AssetStudioSceneBankMetadata metadata) { - try { - writeSceneBankMetadataFile(assetRoot, metadata); - return AssetMetadataWriteResult.success(); - } catch (IOException exception) { - return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception)); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) { + try { + writeSceneBankMetadataFile(assetRoot, metadata); + return AssetMetadataWriteResult.success(); + } catch (IOException exception) { + return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception)); + } } } @@ -91,11 +99,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService { @Override public AssetMetadataWriteResult writeGlyphSpecialization(Path assetRoot, AssetStudioGlyphSpecialization specialization) { - try { - writeGlyphSpecializationFile(assetRoot, specialization); - return AssetMetadataWriteResult.success(); - } catch (IOException exception) { - return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception)); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) { + try { + writeGlyphSpecializationFile(assetRoot, specialization); + return AssetMetadataWriteResult.success(); + } catch (IOException exception) { + return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception)); + } } } @@ -119,11 +129,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService { @Override public AssetMetadataWriteResult writeGlyphMaterialMetadata(Path assetRoot, AssetStudioGlyphMaterialMetadata metadata) { - try { - writeGlyphMaterialMetadataFile(assetRoot, metadata); - return AssetMetadataWriteResult.success(); - } catch (IOException exception) { - return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception)); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) { + try { + writeGlyphMaterialMetadataFile(assetRoot, metadata); + return AssetMetadataWriteResult.success(); + } catch (IOException exception) { + return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception)); + } } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java index 790a28ae..29507e47 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java @@ -23,6 +23,12 @@ import java.util.List; import java.util.Objects; public final class SceneBankWorkflowService implements SceneBankWorkflow { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public SceneBankWorkflowService(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + this(assetCatalog, mapper); + this.access = java.util.Objects.requireNonNull(access); + } + public static final String ACCEPTED_REQUEST_FILE = "scene-bank.pack-request.json"; private final ObjectMapper mapper; @@ -60,10 +66,12 @@ public final class SceneBankWorkflowService implements SceneBankWorkflow { } final List diagnostics = new ArrayList<>(validateDiagnostics(projectReference, details)); if (diagnostics.stream().noneMatch(AssetDiagnostic::blocking)) { - try { + try (var accessLease = access.enterManual(projectReference.rootPath())) { writeAcceptedRequest( details.summary().assetRoot().resolve(ACCEPTED_REQUEST_FILE), buildCanonicalRequest(projectReference, details)); + } catch (p.studio.api.automation.ControlDeniedException locked) { + // Inspection remains available while ceded; do not persist derived requests. } catch (IOException | IllegalArgumentException exception) { diagnostics.add(error( "Unable to persist canonical scene-pack request: " + exception.getMessage(), diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java index 4283c146..a3cac290 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java @@ -25,6 +25,12 @@ import java.util.Map; import java.util.Objects; public final class TiledAssetGenerationService implements TiledAssetService { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public TiledAssetGenerationService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) { + this(metadataService); + this.access = java.util.Objects.requireNonNull(access); + } + public static final String GENERATED_TSX_FILE = "tileset.tsx"; private static final long FLIP_HORIZONTAL_FLAG = 0x80000000L; @@ -49,61 +55,71 @@ public final class TiledAssetGenerationService implements TiledAssetService { } public TiledAssetGenerationResult generateTilesetTsx(AssetWorkspaceAssetDetails details) { - return exportTilesetTsx(details); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportTilesetTsx(details); + } } @Override public TiledAssetGenerationResult exportTilesetTsx(AssetWorkspaceAssetDetails details) { - if (details == null - || details.summary().assetFamily() != AssetFamily.GLYPH_BANK - || details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) { - return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of()); - } - final List selectedFiles = details.bankComposition().selectedFiles(); - if (selectedFiles.isEmpty()) { - return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of()); - } - final int tileSize = parseTileSize(details.metadataFields()); - final List tiles = new ArrayList<>(); - for (int index = 0; index < selectedFiles.size(); index += 1) { - final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index); - tiles.add(new TiledTilesetTile( - index, - file.path(), + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + if (details == null + || details.summary().assetFamily() != AssetFamily.GLYPH_BANK + || details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) { + return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of()); + } + final List selectedFiles = details.bankComposition().selectedFiles(); + if (selectedFiles.isEmpty()) { + return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of()); + } + final int tileSize = parseTileSize(details.metadataFields()); + final List tiles = new ArrayList<>(); + for (int index = 0; index < selectedFiles.size(); index += 1) { + final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index); + tiles.add(new TiledTilesetTile( + index, + file.path(), + tileSize, + tileSize, + List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))), + null)); + } + final TiledTilesetDocument document = new TiledTilesetDocument( + "1.10", + "1.12.1", + details.summary().assetName(), tileSize, tileSize, - List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))), - null)); - } - final TiledTilesetDocument document = new TiledTilesetDocument( - "1.10", - "1.12.1", - details.summary().assetName(), - tileSize, - tileSize, - tiles.size(), - 0, - List.of(), - tiles); - final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE); - try { - codec.writeTileset(outputPath, document); - return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath)); - } catch (IOException exception) { - return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of()); + tiles.size(), + 0, + List.of(), + tiles); + final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE); + try { + codec.writeTileset(outputPath, document); + return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath)); + } catch (IOException exception) { + return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of()); + } } } public TiledAssetGenerationResult generateSceneBankTilemaps(ProjectReference projectReference, AssetWorkspaceAssetDetails details) { - return exportSceneBankTmx(projectReference, details); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportSceneBankTmx(projectReference, details); + } } public TiledAssetGenerationResult generateSceneBankTilemap(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) { - return exportSceneBankTmx(projectReference, details); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportSceneBankTmx(projectReference, details); + } } public TiledAssetGenerationResult exportSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) { - return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE); + } } @Override @@ -111,221 +127,225 @@ public final class TiledAssetGenerationService implements TiledAssetService { ProjectReference projectReference, AssetWorkspaceAssetDetails details, SceneTmxExportDisposition disposition) { - if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { - return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of()); - } - final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); - if (metadata == null) { - return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); - } - final List enabledLayers = metadata.layerBindings().stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .toList(); - if (enabledLayers.isEmpty()) { - return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of()); - } - final String sceneTilemap = resolveSceneTilemap(metadata); - if (sceneTilemap == null) { - return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); - } - try { - final ExportContext context = buildExportContext(projectReference, details, enabledLayers); - final List tileLayers = new ArrayList<>(); - int nextLayerId = 1; - for (AssetStudioSceneLayerBinding binding : enabledLayers) { - final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot()); - final List gids = new ArrayList<>(binding.tiles().size()); - for (AssetStudioSceneTile tile : binding.tiles()) { - if (!tile.active()) { - gids.add(0L); - continue; + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { + return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of()); + } + final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); + if (metadata == null) { + return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); + } + final List enabledLayers = metadata.layerBindings().stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .toList(); + if (enabledLayers.isEmpty()) { + return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of()); + } + final String sceneTilemap = resolveSceneTilemap(metadata); + if (sceneTilemap == null) { + return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); + } + try { + final ExportContext context = buildExportContext(projectReference, details, enabledLayers); + final List tileLayers = new ArrayList<>(); + int nextLayerId = 1; + for (AssetStudioSceneLayerBinding binding : enabledLayers) { + final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot()); + final List gids = new ArrayList<>(binding.tiles().size()); + for (AssetStudioSceneTile tile : binding.tiles()) { + if (!tile.active()) { + gids.add(0L); + continue; + } + if (tile.glyphId() >= ref.tileCount()) { + return new TiledAssetGenerationResult( + false, + "Layer " + binding.index() + " references glyph_id outside the exported TSX range.", + List.of(), + List.of()); + } + long gid = ref.firstGid() + tile.glyphId(); + if (tile.flipX()) { + gid |= FLIP_HORIZONTAL_FLAG; + } + if (tile.flipY()) { + gid |= FLIP_VERTICAL_FLAG; + } + gids.add(gid); } - if (tile.glyphId() >= ref.tileCount()) { - return new TiledAssetGenerationResult( - false, - "Layer " + binding.index() + " references glyph_id outside the exported TSX range.", - List.of(), - List.of()); - } - long gid = ref.firstGid() + tile.glyphId(); - if (tile.flipX()) { - gid |= FLIP_HORIZONTAL_FLAG; - } - if (tile.flipY()) { - gid |= FLIP_VERTICAL_FLAG; - } - gids.add(gid); + tileLayers.add(new TiledTileLayer( + nextLayerId, + binding.layerName(), + binding.width(), + binding.height(), + gids, + List.of())); + nextLayerId += 1; } - tileLayers.add(new TiledTileLayer( + final TiledMapDocument document = new TiledMapDocument( + "1.10", + "1.12.1", + "orthogonal", + "right-down", + enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1), + enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1), + context.tileSize(), + context.tileSize(), nextLayerId, - binding.layerName(), - binding.width(), - binding.height(), - gids, - List.of())); - nextLayerId += 1; + 1, + List.of(), + context.tilesetRefs(), + tileLayers, + List.of()); + final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap); + final ArrayList writtenFiles = new ArrayList<>(); + if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) { + final Path backupPath = nextSceneTmxBackupPath(outputPath); + Files.copy(outputPath, backupPath); + writtenFiles.add(backupPath); + } + codec.writeMap(outputPath, document); + writtenFiles.add(outputPath); + return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles)); + } catch (IOException | TiledUnsupportedFeatureException exception) { + return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of()); } - final TiledMapDocument document = new TiledMapDocument( - "1.10", - "1.12.1", - "orthogonal", - "right-down", - enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1), - enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1), - context.tileSize(), - context.tileSize(), - nextLayerId, - 1, - List.of(), - context.tilesetRefs(), - tileLayers, - List.of()); - final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap); - final ArrayList writtenFiles = new ArrayList<>(); - if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) { - final Path backupPath = nextSceneTmxBackupPath(outputPath); - Files.copy(outputPath, backupPath); - writtenFiles.add(backupPath); - } - codec.writeMap(outputPath, document); - writtenFiles.add(outputPath); - return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles)); - } catch (IOException | TiledUnsupportedFeatureException exception) { - return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of()); } } @Override public TiledAssetGenerationResult importSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) { - if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { - return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of()); - } - final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); - if (metadata == null) { - return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); - } - final String sceneTilemap = resolveSceneTilemap(metadata); - if (sceneTilemap == null) { - return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); - } - final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap); - if (!Files.isRegularFile(inputPath)) { - return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of()); - } - try { - final List enabledLayers = metadata.layerBindings().stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .toList(); - final ExportContext context = buildExportContext(projectReference, details, enabledLayers); - final TiledMapDocument map = codec.readMap(inputPath); - if (map.tileLayers().isEmpty()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { + return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of()); } - if (map.tileLayers().size() > metadata.layerCount()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of()); + final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); + if (metadata == null) { + return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); } - if (map.tilesets().size() != context.tilesetRefs().size()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of()); + final String sceneTilemap = resolveSceneTilemap(metadata); + if (sceneTilemap == null) { + return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); } - for (int index = 0; index < context.tilesetRefs().size(); index += 1) { - if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) { - return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of()); + final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap); + if (!Files.isRegularFile(inputPath)) { + return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of()); + } + try { + final List enabledLayers = metadata.layerBindings().stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .toList(); + final ExportContext context = buildExportContext(projectReference, details, enabledLayers); + final TiledMapDocument map = codec.readMap(inputPath); + if (map.tileLayers().isEmpty()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of()); + } + if (map.tileLayers().size() > metadata.layerCount()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of()); + } + if (map.tilesets().size() != context.tilesetRefs().size()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of()); + } + for (int index = 0; index < context.tilesetRefs().size(); index += 1) { + if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) { + return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of()); + } } - } - final List updatedBindings = new ArrayList<>(); - for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) { - final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex); - if (bindingIndex >= map.tileLayers().size()) { + final List updatedBindings = new ArrayList<>(); + for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) { + final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex); + if (bindingIndex >= map.tileLayers().size()) { + updatedBindings.add(new AssetStudioSceneLayerBinding( + false, + binding.index(), + binding.layerName(), + binding.width(), + binding.height(), + binding.tilemap(), + binding.tilesetAssetRoot(), + binding.parallaxFactorX(), + binding.parallaxFactorY(), + binding.defaultPaletteId(), + binding.tiles())); + continue; + } + final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex); + if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of()); + } + final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context); + if (ref == null) { + return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of()); + } + final List importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height()); + for (long rawGid : importedLayer.gids()) { + if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) { + return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of()); + } + final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L; + final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L; + final long gid = rawGid & GID_MASK; + if (gid == 0L) { + importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId())); + continue; + } + if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of()); + } + final int tilesetTileId = (int) (gid - ref.firstGid()); + final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId); + if (glyphId == null) { + return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of()); + } + importedTiles.add(new AssetStudioSceneTile( + true, + glyphId, + binding.defaultPaletteId(), + flipX, + flipY)); + } updatedBindings.add(new AssetStudioSceneLayerBinding( - false, + true, binding.index(), binding.layerName(), - binding.width(), - binding.height(), + importedLayer.width(), + importedLayer.height(), binding.tilemap(), - binding.tilesetAssetRoot(), + ref.assetRoot(), binding.parallaxFactorX(), binding.parallaxFactorY(), binding.defaultPaletteId(), - binding.tiles())); - continue; + importedTiles)); } - final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex); - if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of()); + final int mapWidth = Math.max(map.width(), updatedBindings.stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .mapToInt(AssetStudioSceneLayerBinding::width) + .max() + .orElse(metadata.mapWidth())); + final int mapHeight = Math.max(map.height(), updatedBindings.stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .mapToInt(AssetStudioSceneLayerBinding::height) + .max() + .orElse(metadata.mapHeight())); + final var metadataWrite = metadataService.writeSceneBankMetadata( + details.summary().assetRoot(), new AssetStudioSceneBankMetadata( + mapWidth, + mapHeight, + metadata.layerCount(), + updatedBindings, + metadata.supportFile())); + if (!metadataWrite.successful()) { + return new TiledAssetGenerationResult( + false, + "Unable to import TMX: " + metadataWrite.message(), + List.of(), + List.of()); } - final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context); - if (ref == null) { - return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of()); - } - final List importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height()); - for (long rawGid : importedLayer.gids()) { - if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) { - return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of()); - } - final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L; - final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L; - final long gid = rawGid & GID_MASK; - if (gid == 0L) { - importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId())); - continue; - } - if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of()); - } - final int tilesetTileId = (int) (gid - ref.firstGid()); - final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId); - if (glyphId == null) { - return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of()); - } - importedTiles.add(new AssetStudioSceneTile( - true, - glyphId, - binding.defaultPaletteId(), - flipX, - flipY)); - } - updatedBindings.add(new AssetStudioSceneLayerBinding( - true, - binding.index(), - binding.layerName(), - importedLayer.width(), - importedLayer.height(), - binding.tilemap(), - ref.assetRoot(), - binding.parallaxFactorX(), - binding.parallaxFactorY(), - binding.defaultPaletteId(), - importedTiles)); + return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile())); + } catch (IOException | TiledUnsupportedFeatureException exception) { + return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of()); } - final int mapWidth = Math.max(map.width(), updatedBindings.stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .mapToInt(AssetStudioSceneLayerBinding::width) - .max() - .orElse(metadata.mapWidth())); - final int mapHeight = Math.max(map.height(), updatedBindings.stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .mapToInt(AssetStudioSceneLayerBinding::height) - .max() - .orElse(metadata.mapHeight())); - final var metadataWrite = metadataService.writeSceneBankMetadata( - details.summary().assetRoot(), new AssetStudioSceneBankMetadata( - mapWidth, - mapHeight, - metadata.layerCount(), - updatedBindings, - metadata.supportFile())); - if (!metadataWrite.successful()) { - return new TiledAssetGenerationResult( - false, - "Unable to import TMX: " + metadataWrite.message(), - List.of(), - List.of()); - } - return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile())); - } catch (IOException | TiledUnsupportedFeatureException exception) { - return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of()); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java index 4daf71a7..c837946f 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java @@ -15,15 +15,18 @@ public final class DefaultExecutionControllerFactory implements ExecutionControl private final Shipper shipper; private final RuntimeGateway runtime; private final OperationExecutor operations; + private final p.studio.api.automation.ProjectAccess access; - public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) { + public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations, + p.studio.api.automation.ProjectAccess access) { this.shipper = Objects.requireNonNull(shipper, "shipper"); this.runtime = Objects.requireNonNull(runtime, "runtime"); this.operations = Objects.requireNonNull(operations, "operations"); + this.access = Objects.requireNonNull(access); } @Override public ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session) { - return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations); + return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations, access); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java index a05ac817..3248b0fa 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java @@ -30,15 +30,24 @@ final class PlayStopExecutionController implements ExecutionController { private OperationHandle activeOperation; private OperationHandle preparationOperation; private boolean stopRequested; + private final p.studio.api.automation.ProjectAccess access; + private p.studio.api.automation.ManualLease manualLease; PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) { + this(project, setup, session, shipper, runtime, operations, new p.studio.core.project.ProjectAccessRegistry()); + } + + PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup, + ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations, + p.studio.api.automation.ProjectAccess access) { this.project = Objects.requireNonNull(project, "project"); this.setup = Objects.requireNonNull(setup, "setup"); this.session = Objects.requireNonNull(session, "session"); this.shipper = Objects.requireNonNull(shipper, "shipper"); this.runtime = Objects.requireNonNull(runtime, "runtime"); this.operations = Objects.requireNonNull(operations, "operations"); + this.access = Objects.requireNonNull(access); } @Override @@ -47,9 +56,17 @@ final class PlayStopExecutionController implements ExecutionController { if (isBusy(session.snapshot().state()) && activeOperation != null) { return activeOperation; } + if (manualLease != null) throw new p.studio.api.automation.ControlDeniedException( + p.studio.api.automation.ControlResult.Status.BUSY); + manualLease = access.enterManual(project.rootPath()); + manualLease.onProjectClose(this::stop); stopRequested = false; session.beginPreparationCycle(); - activeOperation = operations.submit("Run " + project.name(), this::runPlay); + try { activeOperation = operations.submit("Run " + project.name(), this::runPlay); } + catch (RuntimeException failure) { releaseManual(); throw failure; } + activeOperation.termination().whenComplete((v, f) -> { + synchronized (monitor) { if (!isBusy(session.snapshot().state()) || stopRequested) releaseManual(); } + }); return activeOperation; } } @@ -74,6 +91,7 @@ final class PlayStopExecutionController implements ExecutionController { if (state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING) { session.transitionToStopped(); } + if (execution == null || execution.termination().toCompletableFuture().isDone()) releaseManual(); } @Override @@ -141,8 +159,10 @@ final class PlayStopExecutionController implements ExecutionController { private void handleExit(RuntimeConnection started, Integer exitCode, Throwable failure) { final boolean stopped; synchronized (monitor) { - if (connection == started) connection = null; + if (connection != started) return; + connection = null; stopped = stopRequested; + releaseManual(); } if (stopped || session.snapshot().state() == ExecutionState.STOPPED) return; if (failure == null && exitCode != null && exitCode == 0) { @@ -159,6 +179,12 @@ final class PlayStopExecutionController implements ExecutionController { return state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING; } + private void releaseManual() { + synchronized (monitor) { + if (manualLease != null) { manualLease.close(); manualLease = null; } + } + } + private static String message(Throwable failure) { return failure.getMessage() == null || failure.getMessage().isBlank() ? failure.getClass().getSimpleName() : failure.getMessage(); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java new file mode 100644 index 00000000..4b5748a9 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java @@ -0,0 +1,42 @@ +package p.studio.core.project; + +import p.studio.api.automation.ManualLease; +import p.studio.api.automation.ProjectAccess; +import p.studio.api.operation.OperationSubscription; +import java.nio.file.Path; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +/** Application-composed routing only; authority is owned by each project session. */ +public final class ProjectAccessRegistry implements ProjectAccess { + private final Map> projects = new HashMap<>(); + + public synchronized OperationSubscription register(Path root, Supplier authority) { + Path key = canonical(root); + if (projects.putIfAbsent(key, authority) != null) throw new IllegalStateException("Project already open: " + key); + return () -> { synchronized (this) { projects.remove(key, authority); } }; + } + + @Override public ManualLease enterManual(Path path) { + Supplier authority; + synchronized (this) { + Path key = canonical(path); + authority = projects.entrySet().stream().filter(e -> key.startsWith(e.getKey())) + .max(java.util.Comparator.comparingInt(e -> e.getKey().getNameCount())) + .map(Map.Entry::getValue).orElse(null); + } + // Project creation/setup before opening a session is still a manual workflow. + return authority == null ? () -> {} : authority.get(); + } + + private static Path canonical(Path path) { + Path normalized = path.toAbsolutePath().normalize(); + try { return normalized.toRealPath(); } + catch (IOException ignored) { + Path parent = normalized.getParent(); + return parent == null ? normalized : canonical(parent).resolve(normalized.getFileName()); + } + } +} 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 new file mode 100644 index 00000000..9b1a3544 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java @@ -0,0 +1,243 @@ +package p.studio.core.session; + +import p.studio.api.automation.*; +import p.studio.api.operation.*; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.Consumer; + +/** Project authority is independent of any UI, transport connection or operation result. */ +public final class DefaultAutomationSession implements AutomationSession { + private final Path root; + private final OperationExecutor executor; + private final List> listeners = new CopyOnWriteArrayList<>(); + private final List documents = new CopyOnWriteArrayList<>(); + private final Deque calls = new ArrayDeque<>(); + private ControlState state = ControlState.MANUAL; + private TaskIdentity task; + private int manualOperations; + private boolean handoffPending, closed, busy, stale; + private long generation; + private OperationHandle active; + private ManagedHeadlessSession runtime; + private CanonicalCapture capture; + private List diagnostics = List.of(); + private CompletableFuture returning; + private final List manualCancellation = new ArrayList<>(); + private CompletableFuture manualIdle = CompletableFuture.completedFuture(null); + + public DefaultAutomationSession(Path root, OperationExecutor executor) { + this.root = root.toAbsolutePath().normalize(); + this.executor = Objects.requireNonNull(executor); + } + + public synchronized ManualLease enterManual() { + if (closed) throw new ControlDeniedException(ControlResult.Status.CLOSED); + if (state != ControlState.MANUAL) throw new ControlDeniedException(ControlResult.Status.BUSY); + if (manualOperations++ == 0) manualIdle = new CompletableFuture<>(); + stale = capture != null; + publish(); + return new ManualLease() { + private boolean released; + private Runnable cancellation; + @Override public void onProjectClose(Runnable action) { + boolean cancel; + synchronized (DefaultAutomationSession.this) { + if (released) return; + cancellation = action; + manualCancellation.add(action); + cancel = closed; + } + if (cancel) action.run(); + } + @Override public void close() { + synchronized (DefaultAutomationSession.this) { + if (!released) { + released = true; manualCancellation.remove(cancellation); + if (--manualOperations == 0) manualIdle.complete(null); + publish(); + } + } + } + }; + } + + @Override public synchronized AutomationSnapshot snapshot() { + return new AutomationSnapshot(root, state, handoffPending, closed, manualOperations, task, + active == null ? null : active.snapshot(), capture, stale, diagnostics, List.copyOf(calls)); + } + + @Override public OperationSubscription subscribe(Consumer listener) { + listeners.add(listener); notifyListener(listener, snapshot()); + return () -> listeners.remove(listener); + } + + @Override public OperationSubscription registerDocuments(DocumentHandoff participant) { + documents.add(Objects.requireNonNull(participant)); + return () -> { if (documents.remove(participant)) participant.close(); }; + } + + @Override public CompletionStage grant(boolean save) { + final long attempt; + final List participants; + synchronized (this) { + if (closed) return result(ControlResult.Status.CLOSED, "Project closed"); + if (state != ControlState.MANUAL || handoffPending || manualOperations != 0) + return result(ControlResult.Status.BUSY, "Manual work or another control transition is active"); + handoffPending = true; attempt = ++generation; + participants = List.copyOf(documents); publish(); + } + CompletableFuture dirty = CompletableFuture.completedFuture(false); + for (var participant : participants) + dirty = dirty.thenCompose(found -> participant.hasUnsavedChanges().thenApply(next -> found || next)).toCompletableFuture(); + return dirty.thenCompose(found -> { + if (found && !save) return result(ControlResult.Status.DIRTY_DOCUMENTS, "Save all and grant, or cancel"); + CompletionStage saved = CompletableFuture.completedFuture(null); + if (found) for (var participant : participants) saved = saved.thenCompose(v -> participant.saveAll()); + return saved.thenCompose(v -> verifySaved(participants)).thenApply(v -> { + synchronized (this) { + if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); + if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active"); + state = ControlState.WAITING_FOR_AGENT; + record("grant"); + return ControlResult.of(ControlResult.Status.GRANTED, ""); + } + }); + }).exceptionally(f -> ControlResult.of(ControlResult.Status.SAVE_FAILED, message(f))) + .thenApply(outcome -> { + synchronized (this) { + if (generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); + handoffPending = false; + diagnostics = outcome.success() ? List.of() : List.of(outcome.diagnostic()); + publish(); return outcome; + } + }); + } + + private CompletionStage verifySaved(List participants) { + CompletionStage check = CompletableFuture.completedFuture(null); + for (var p : participants) check = check.thenCompose(v -> p.hasUnsavedChanges().thenAccept(dirty -> { + if (dirty) throw new IllegalStateException("Document save did not finish successfully"); + })); + return check; + } + + @Override public synchronized ControlResult acquire() { + if (closed) return ControlResult.of(ControlResult.Status.CLOSED, "Project closed"); + if (state != ControlState.WAITING_FOR_AGENT) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required"); + task = new TaskIdentity(root, UUID.randomUUID().toString()); + state = ControlState.AGENT_WORKING; record("acquire"); publish(); + return new ControlResult(ControlResult.Status.ACQUIRED, task, ""); + } + + @Override public CompletionStage release(TaskIdentity identity) { + return beginReturn(false, identity, true); + } + @Override public CompletionStage reclaim() { return beginReturn(false, null, false); } + @Override public CompletionStage closeAsync() { + var cleanup = beginReturn(true, null, false); + for (var participant : List.copyOf(documents)) { + if (documents.remove(participant)) participant.close(); + } + return cleanup; + } + + private CompletionStage beginReturn(boolean closing, TaskIdentity identity, boolean requireIdentity) { + final CompletableFuture result; + final OperationHandle operation; + final ManagedHeadlessSession ownedRuntime; + final List cancellations; + final List participants; + final CompletableFuture idle; + synchronized (this) { + if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current"); + if (closing) closed = true; + if (returning != null && !returning.isDone()) return returning; + if (!closing && state == ControlState.MANUAL) return result(ControlResult.Status.RETURNED, ""); + state = ControlState.RETURNING_CONTROL; task = null; generation++; handoffPending = false; + record(closing ? "close" : "reclaim"); stale = capture != null; + result = returning = new CompletableFuture<>(); + operation = active; ownedRuntime = runtime; idle = manualIdle; + cancellations = closing ? List.copyOf(manualCancellation) : List.of(); + participants = closing ? List.of() : List.copyOf(documents); + publish(); + } + // Never call another service while holding the authority monitor: Debug owns its own lock. + CompletionStage cleanup; + try { + for (var cancellation : cancellations) cancellation.run(); + if (operation != null) operation.cancel(); + CompletionStage stopped = operation == null ? CompletableFuture.completedFuture(null) : operation.termination(); + CompletionStage shutdown = CompletableFuture.completedFuture(null); + if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(); } + cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle); + // 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); } + return p.refreshFromDisk(); + }); + } catch (RuntimeException failure) { cleanup = CompletableFuture.failedFuture(failure); } + cleanup.whenComplete((v, failure) -> { + synchronized (this) { + if (failure == null) { + runtime = null; busy = false; state = ControlState.MANUAL; + diagnostics = List.of(); publish(); + result.complete(ControlResult.of(ControlResult.Status.RETURNED, "")); + } else { + diagnostics = List.of(message(failure)); publish(); + result.complete(ControlResult.of(ControlResult.Status.CLEANUP_FAILED, message(failure))); + } + } + }); + return result; + } + + @Override public synchronized OperationHandle submit(TaskIdentity identity, String summary, + Callable work) { + requireTask(identity); + if (busy) throw new ControlDeniedException(ControlResult.Status.BUSY); + busy = true; record(summary); + try { active = executor.submit(summary, work); } + catch (RuntimeException failure) { busy = false; throw failure; } + var operation = active; + var subscription = operation.subscribe(s -> { synchronized (this) { if (active == operation) publish(); } }); + operation.completion().whenComplete((outcome, failure) -> { + synchronized (this) { + if (!valid(identity) || active != operation) return; + diagnostics = failure != null ? List.of(message(failure)) : outcome.diagnostics(); + if (outcome != null && outcome.capture() != null && runtime != null + && runtime.sessionId().equals(outcome.capture().sessionId())) { + capture = outcome.capture(); stale = false; + } + publish(); + } + }); + operation.termination().whenComplete((v, f) -> { + subscription.unsubscribe(); + synchronized (this) { if (active == operation) { busy = false; publish(); } } + }); + publish(); return operation; + } + + @Override public synchronized void attachRuntime(TaskIdentity identity, ManagedHeadlessSession next) { + requireTask(identity); + if (runtime != null) throw new ControlDeniedException(ControlResult.Status.BUSY); + runtime = Objects.requireNonNull(next); stale = capture != null; record("runtime " + next.sessionId()); publish(); + } + @Override public synchronized void markCaptureStale() { 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(); } + private void publish() { var value = snapshot(); listeners.forEach(l -> notifyListener(l, value)); } + private static void notifyListener(Consumer listener, AutomationSnapshot value) { + try { listener.accept(value); } catch (RuntimeException ignored) { /* Observation cannot change authority. */ } + } + private static CompletionStage result(ControlResult.Status status, String text) { + return CompletableFuture.completedFuture(ControlResult.of(status, text)); + } + private static String message(Throwable failure) { + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + return Objects.requireNonNullElse(failure.getMessage(), failure.getClass().getSimpleName()); + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java index 976ac425..930e1175 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java @@ -17,30 +17,39 @@ public final class DefaultProjectSession implements ProjectSession { private final LspLifecyclePort lsp; private ProjectLocalStudioState state; private boolean closed; + private final DefaultAutomationSession automation; + private final p.studio.api.operation.OperationSubscription accessRegistration; DefaultProjectSession(ProjectReference project, ProjectLocalStudioStateStore stateStore, ProjectLocalStudioSetup setup, ExecutionSession execution, LspLifecyclePort lsp, - ProjectLocalStudioState state) { + ProjectLocalStudioState state, DefaultAutomationSession automation, + p.studio.api.operation.OperationSubscription accessRegistration) { this.project = Objects.requireNonNull(project, "project"); this.stateStore = Objects.requireNonNull(stateStore, "stateStore"); this.setup = Objects.requireNonNull(setup, "setup"); this.execution = Objects.requireNonNull(execution, "execution"); this.lsp = Objects.requireNonNull(lsp, "lsp"); this.state = Objects.requireNonNull(state, "state"); + this.automation = Objects.requireNonNull(automation); + this.accessRegistration = Objects.requireNonNull(accessRegistration); } @Override public ProjectReference projectReference() { return project; } @Override public ProjectLocalStudioState projectLocalStudioState() { return state; } @Override public ProjectLocalStudioSetup projectLocalStudioSetup() { return setup; } @Override public ExecutionSession executionSession() { return execution; } + @Override public p.studio.api.automation.AutomationSession automation() { return automation; } @Override public void replaceProjectLocalStudioState(ProjectLocalStudioState next) { state = Objects.requireNonNull(next, "state"); } @Override public void saveProjectLocalStudioState() { stateStore.save(project, state); } @Override public synchronized void close() { if (closed) return; + var cleanup = automation.closeAsync().toCompletableFuture().join(); + if (!cleanup.success()) throw new IllegalStateException(cleanup.diagnostic()); closed = true; - RuntimeException failure = attempt(this::saveProjectLocalStudioState, null); + RuntimeException failure = attempt(accessRegistration::unsubscribe, null); + failure = attempt(this::saveProjectLocalStudioState, failure); failure = attempt(execution::close, failure); failure = attempt(() -> lsp.shutdown(project), failure); if (failure != null) throw failure; diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index db6ffba6..627337b3 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -13,12 +13,17 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory private final ProjectLocalStudioStateStore stateStore; private final ProjectLocalStudioSetupStore setupStore; private final LspLifecyclePort lsp; + private final p.studio.core.project.ProjectAccessRegistry access; + private final p.studio.api.operation.OperationExecutor operations; public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore, - ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) { + ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, + p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations) { this.stateStore = Objects.requireNonNull(stateStore, "stateStore"); this.setupStore = Objects.requireNonNull(setupStore, "setupStore"); this.lsp = Objects.requireNonNull(lsp, "lsp"); + this.access = Objects.requireNonNull(access); + this.operations = Objects.requireNonNull(operations); } @Override @@ -26,7 +31,10 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference"); final var setup = setupStore.load(project); final var state = stateStore.load(project); - lsp.boot(project); - return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state); + var automation = new DefaultAutomationSession(project.rootPath(), operations); + var registration = access.register(project.rootPath(), automation::enterManual); + try { lsp.boot(project); } + catch (RuntimeException failure) { registration.unsubscribe(); throw failure; } + return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, registration); } } 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 08ddcd9b..f44d6570 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 @@ -28,6 +28,12 @@ import java.util.Objects; import java.util.function.Consumer; public final class StudioShipperService implements Shipper { + 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); + this.access = java.util.Objects.requireNonNull(access); + } + private final CompilerBuildGateway compiler; private final PackerWorkspaceService packer; private final ObjectMapper mapper; @@ -45,7 +51,7 @@ public final class StudioShipperService implements Shipper { public OperationHandle prepare(ProjectReference project, Consumer sink) { Objects.requireNonNull(project, "project"); Objects.requireNonNull(sink, "sink"); - return operations.submit("Build and pack " + project.name(), () -> prepareNow(project, sink)); + return access.submitManual(project.rootPath(), operations, "Build and pack " + project.name(), () -> prepareNow(project, sink)); } private ShipperPrepareResult prepareNow(ProjectReference project, Consumer sink) { diff --git a/prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java b/prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java new file mode 100644 index 00000000..5c7efde3 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java @@ -0,0 +1,51 @@ +package p.studio.core.assets; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.packer.PackerWorkspaceService; +import p.studio.api.assets.*; +import p.studio.api.assets.metadata.AssetStudioGlyphSpecialization; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.core.assets.metadata.AssetStudioMetadataService; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.core.support.ControlledOperations; +import java.nio.file.*; +import static org.junit.jupiter.api.Assertions.*; + +class AssetAuthorityTest { + @TempDir Path root; + @Test void actualMutatorsRejectDirectCallsButInspectionRemainsAvailable() { + var access = new ProjectAccessRegistry(); + var automation = new DefaultAutomationSession(root, new ControlledOperations()); + access.register(root, automation::enterManual); + var project = new ProjectReference("Test", "1", "pbs", 1, ProjectTarget.Game, root); + var packer = (PackerWorkspaceService) java.lang.reflect.Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[]{PackerWorkspaceService.class}, + (proxy, method, args) -> { throw new AssertionError("Rejected call reached packer: " + method); }); + var commands = new PackerAssetCommands(packer, access); + var packing = new PackerAssetPacking(packer, new ControlledOperations(), access); + var shipper = new p.studio.core.shipper.StudioShipperService((p, log) -> { throw new AssertionError("must not compile"); }, + packer, new ObjectMapper(), new ControlledOperations(), access); + var storage = new FileSystemAssetWorkspaceStorage(access); + var metadata = new AssetStudioMetadataService(new ObjectMapper(), access); + automation.grant(false).toCompletableFuture().join(); + for (int state = 0; state < 2; state++) { + assertThrows(ControlDeniedException.class, () -> commands.delete(project, AssetReference.of("test"))); + assertThrows(ControlDeniedException.class, () -> commands.register(project, AssetReference.of("test"))); + assertThrows(ControlDeniedException.class, () -> storage.prepare(project)); + assertThrows(ControlDeniedException.class, () -> packing.pack(project)); + assertThrows(ControlDeniedException.class, () -> packing.deepSync(project)); + assertThrows(ControlDeniedException.class, () -> shipper.prepare(project, log -> {})); + assertThrows(ControlDeniedException.class, () -> metadata.writeGlyphSpecialization(root, AssetStudioGlyphSpecialization.NONE)); + assertFalse(storage.assetManifestExists(project, "missing")); + assertNotNull(metadata.read(root, AssetFamily.GLYPH_BANK)); + automation.acquire(); + } + assertFalse(Files.exists(root.resolve("assets"))); + automation.reclaim().toCompletableFuture().join(); + assertTrue(storage.prepare(project).success()); + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java b/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java index 8e098589..5a2e49a1 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java @@ -39,6 +39,38 @@ import static org.junit.jupiter.api.Assertions.assertTrue; final class PlayStopExecutionControllerTest { private static final OperationExecutor OPERATIONS = new ImmediateOperationExecutor(); + @Test + void debugAndAutomationAreMutuallyExclusiveAndLateExitCannotUnlockNewDebug() { + var authority = new p.studio.core.session.DefaultAutomationSession(project().rootPath(), OPERATIONS); + var access = new p.studio.core.project.ProjectAccessRegistry(); + access.register(project().rootPath(), authority::enterManual); + var session = new DefaultExecutionSession(); + var exits = new java.util.ArrayList>(); + RuntimeGateway runtime = (project, setup, logs) -> { + var exit = new CompletableFuture(); exits.add(exit); + return new RuntimeConnection() { + public CompletableFuture completion() { return exit; } + public void close() { } // Exit notification can arrive after close returned. + }; + }; + var controller = new PlayStopExecutionController(project(), ProjectLocalStudioSetup.defaults(), + session, successfulShipper(), runtime, OPERATIONS, access); + controller.play(); + assertEquals(p.studio.api.automation.ControlResult.Status.BUSY, authority.grant(false).toCompletableFuture().join().status()); + controller.stop(); controller.play(); exits.getFirst().complete(0); + assertEquals(ExecutionState.RUNNING, session.snapshot().state()); + assertEquals(1, authority.snapshot().manualOperations()); + controller.stop(); + assertEquals(p.studio.api.automation.ControlResult.Status.GRANTED, authority.grant(false).toCompletableFuture().join().status()); + org.junit.jupiter.api.Assertions.assertThrows(p.studio.api.automation.ControlDeniedException.class, controller::play); + authority.acquire(); + org.junit.jupiter.api.Assertions.assertThrows(p.studio.api.automation.ControlDeniedException.class, controller::play); + authority.reclaim().toCompletableFuture().join(); + controller.play(); + authority.closeAsync().toCompletableFuture().join(); + assertEquals(ExecutionState.STOPPED, session.snapshot().state()); + } + @Test void successfulPreparationStartsRuntimeAndProjectsExit() { final var session = new DefaultExecutionSession(); diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java new file mode 100644 index 00000000..b1533bc1 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java @@ -0,0 +1,185 @@ +package p.studio.core.session; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.support.ControlledOperations; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; +import static p.studio.api.automation.ControlResult.Status.*; + +class DefaultAutomationSessionTest { + @TempDir Path root; + final ControlledOperations operations = new ControlledOperations(); + DefaultAutomationSession session() { return new DefaultAutomationSession(root, operations); } + ControlResult await(CompletionStage result) { return result.toCompletableFuture().join(); } + TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); } + + @Test void explicitGrantAndProjectScopedIdentityAreRequired() { + var s = session(); + assertEquals(NOT_GRANTED, s.acquire().status()); + var task = start(s); + assertEquals(NOT_GRANTED, s.acquire().status()); + assertEquals(INVALID_TASK, await(s.release(new TaskIdentity(root.resolve("other"), task.value()))).status()); + assertThrows(ControlDeniedException.class, s::enterManual); + assertEquals(RETURNED, await(s.release(task)).status()); + var next = start(s); + assertNotEquals(task, next); + assertEquals(INVALID_TASK, await(s.release(task)).status()); + assertEquals(ControlState.AGENT_WORKING, s.snapshot().state()); + } + + @Test void racingClientsCannotBothAcquireAndWaitingGrantCanBeReclaimed() throws Exception { + var s = session(); s.grant(false).toCompletableFuture().join(); + assertEquals(RETURNED, await(s.reclaim()).status()); assertEquals(NOT_GRANTED, s.acquire().status()); + s.grant(false).toCompletableFuture().join(); + var pool = Executors.newFixedThreadPool(2); + try { + var a = pool.submit(s::acquire); var b = pool.submit(s::acquire); + assertEquals(1, java.util.stream.Stream.of(a.get(), b.get()).filter(r -> r.status() == ACQUIRED).count()); + } finally { pool.shutdownNow(); } + } + + @Test void captureFromWrongRuntimeIsNotPublished() { + var s = session(); var task = start(s); s.attachRuntime(task, new Runtime()); + s.submit(task, "wrong frame", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), + new CanonicalCapture("other-session", "build", 0, 0, 1, 1, 1, new byte[]{1}))); + operations.last.finish(); assertNull(s.snapshot().capture()); + } + + @Test void closureDisposesPendingRefreshWithoutWaitingForPresentationThread() { + var s = session(); var docs = new Documents() { + @Override public void close() { refresh.complete(null); } + }; + docs.refresh = new CompletableFuture<>(); + var registration = s.registerDocuments(docs); start(s); + var returned = s.reclaim().toCompletableFuture(); assertFalse(returned.isDone()); + assertEquals(RETURNED, await(s.closeAsync()).status()); + registration.unsubscribe(); + assertEquals(RETURNED, returned.join().status()); assertFalse(s.snapshot().manualAllowed()); + } + + @Test void manualAndAgentAcquisitionRaceHasOnlyOneWinner() throws Exception { + for (int n = 0; n < 100; n++) { + var s = session(); + var gate = new CountDownLatch(1); + var workers = Executors.newFixedThreadPool(2); + try { + var manual = workers.submit(() -> { gate.await(); try { return s.enterManual(); } catch (ControlDeniedException denied) { return null; } }); + var grant = workers.submit(() -> { gate.await(); return await(s.grant(false)); }); + gate.countDown(); + var lease = manual.get(2, TimeUnit.SECONDS); + var granted = grant.get(2, TimeUnit.SECONDS).status() == GRANTED; + assertNotEquals(lease != null, granted); + if (lease != null) lease.close(); + } finally { workers.shutdownNow(); } + } + } + + @Test void dirtyDocumentsRequireSuccessfulSaveAndRefreshBeforeManualReturn() { + var s = session(); var docs = new Documents(); docs.dirty = true; + s.registerDocuments(docs); + assertEquals(DIRTY_DOCUMENTS, await(s.grant(false)).status()); + assertTrue(s.snapshot().manualAllowed()); assertEquals(0, docs.saves); + docs.failSave = true; + assertEquals(SAVE_FAILED, await(s.grant(true)).status()); + assertTrue(docs.dirty); assertTrue(s.snapshot().manualAllowed()); + docs.failSave = false; + assertEquals(GRANTED, await(s.grant(true)).status()); + assertFalse(docs.dirty); + docs.refresh = new CompletableFuture<>(); + var returned = s.reclaim().toCompletableFuture(); + assertEquals(ControlState.RETURNING_CONTROL, s.snapshot().state()); + assertFalse(returned.isDone()); assertFalse(s.snapshot().manualAllowed()); + docs.refresh.complete(null); + assertEquals(RETURNED, returned.join().status()); assertTrue(s.snapshot().manualAllowed()); + } + + @Test void revocationInvalidatesFirstAndWaitsForWorkerAndRuntimeBeforeRefresh() { + var s = session(); var docs = new Documents(); s.registerDocuments(docs); + var task = start(s); var runtime = new Runtime(); s.attachRuntime(task, runtime); + var capture = new CanonicalCapture("session", "build", 20, 7, 2, 2, 2, new byte[]{1}); + s.submit(task, "advance", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 20, 20, List.of(), capture)); + assertThrows(ControlDeniedException.class, () -> s.submit(task, "overlap", () -> null)); + var returned = s.reclaim().toCompletableFuture(); + assertNull(s.snapshot().task()); assertTrue(operations.last.cancelled); assertTrue(runtime.cancelled); + assertThrows(ControlDeniedException.class, () -> s.submit(task, "late", () -> null)); + assertEquals(0, docs.refreshes); + operations.last.finish(); // A late successful completion must not publish a frame. + assertNull(s.snapshot().capture()); assertFalse(returned.isDone()); + runtime.stopped.complete(null); + assertEquals(RETURNED, returned.join().status()); assertEquals(1, docs.refreshes); + } + + @Test void guestFaultAndCancellationDoNotRevokeAuthorityAndCaptureIsImmutable() { + var s = session(); var task = start(s); var runtime = new Runtime(); s.attachRuntime(task, runtime); + byte[] bytes = {1, 2}; var frame = new CanonicalCapture("session", "build", 9, 4, 2, 2, 2, bytes); + bytes[0] = 8; frame.png()[0] = 9; + assertEquals(1, frame.png()[0]); + s.submit(task, "fault", () -> new AutomationOutcome(AutomationOutcome.Kind.GUEST_FAULT, 10, 9, List.of("fault"), frame)); + operations.last.finish(); + assertEquals(ControlState.AGENT_WORKING, s.snapshot().state()); assertEquals(frame, s.snapshot().capture()); + assertEquals(List.of("fault"), s.snapshot().diagnostics()); + s.markCaptureStale(); assertTrue(s.snapshot().stale()); + s.submit(task, "cancel", () -> new AutomationOutcome(AutomationOutcome.Kind.CANCELLED, 10, 0, List.of(), null)).cancel(); + operations.last.finish(); assertEquals(task, s.snapshot().task()); + } + + @Test void failedCleanupKeepsGuardAndHumanCanRetry() { + var s = session(); var docs = new Documents(); s.registerDocuments(docs); start(s); + docs.refresh = CompletableFuture.failedFuture(new IllegalStateException("disk unavailable")); + assertEquals(CLEANUP_FAILED, await(s.reclaim()).status()); + assertThrows(ControlDeniedException.class, s::enterManual); + docs.refresh = CompletableFuture.completedFuture(null); + assertEquals(RETURNED, await(s.reclaim()).status()); assertTrue(s.snapshot().manualAllowed()); + } + + @Test void registryIsPerProjectAndClosedAuthorityCannotBeReused() { + var registry = new ProjectAccessRegistry(); var s = session(); + var registration = registry.register(root, s::enterManual); start(s); + assertThrows(ControlDeniedException.class, () -> registry.enterManual(root.resolve("assets/new"))); + try (var unrelated = registry.enterManual(root.resolveSibling("unrelated"))) { assertNotNull(unrelated); } + await(s.closeAsync()); assertEquals(CLOSED, s.acquire().status()); + assertThrows(ControlDeniedException.class, () -> registry.enterManual(root)); + registration.unsubscribe(); var reopened = session(); registry.register(root, reopened::enterManual); + try (var manual = registry.enterManual(root)) { assertEquals(1, reopened.snapshot().manualOperations()); } + } + + @Test void closeCancelsManualWorkWithoutCallingItUnderAuthorityLock() throws Exception { + var s = session(); var lease = s.enterManual(); + lease.onProjectClose(() -> { + var worker = CompletableFuture.runAsync(() -> { s.snapshot(); lease.close(); }); + assertDoesNotThrow(() -> worker.get(2, TimeUnit.SECONDS)); + }); + assertEquals(RETURNED, await(s.closeAsync()).status()); assertTrue(s.snapshot().closed()); + assertFalse(s.snapshot().manualAllowed()); + } + + @Test void closeDuringSaveCannotGrantAfterProjectHasClosed() { + var s = session(); var docs = new Documents(); docs.dirty = true; docs.save = new CompletableFuture<>(); + s.registerDocuments(docs); var grant = s.grant(true); + assertTrue(s.snapshot().handoffPending()); await(s.closeAsync()); docs.save.complete(null); + assertEquals(CLOSED, await(grant).status()); assertTrue(s.snapshot().closed()); + } + + static class Documents implements DocumentHandoff { + boolean dirty, failSave; int saves, refreshes; + CompletableFuture save = CompletableFuture.completedFuture(null), refresh = CompletableFuture.completedFuture(null); + public CompletionStage hasUnsavedChanges() { return CompletableFuture.completedFuture(dirty); } + public CompletionStage saveAll() { + saves++; + if (failSave) return CompletableFuture.failedFuture(new IllegalStateException("save failed")); + return save.thenRun(() -> dirty = false); + } + public CompletionStage refreshFromDisk() { refreshes++; return refresh; } + } + static class Runtime implements ManagedHeadlessSession { + final CompletableFuture stopped = new CompletableFuture<>(); boolean cancelled; + public String sessionId() { return "session"; } + public void cancel() { cancelled = true; } + public CompletionStage shutdown() { return stopped; } + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java index 712008bb..f80b95d0 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java @@ -22,7 +22,8 @@ final class DefaultProjectSessionTest { final var stateStore = new ProjectLocalStudioStateStore(mapper); final var setupStore = new ProjectLocalStudioSetupStore(mapper); final var lsp = new RecordingLsp(); - final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp); + final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp, + new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations()); final var project = project(); final var session = factory.open(project); @@ -44,7 +45,8 @@ final class DefaultProjectSessionTest { lsp.failShutdown = true; final var session = new DefaultProjectSessionFactory( new ProjectLocalStudioStateStore(mapper), - new ProjectLocalStudioSetupStore(mapper), lsp).open(project()); + new ProjectLocalStudioSetupStore(mapper), lsp, + new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations()).open(project()); final var failure = assertThrows(IllegalStateException.class, session::close); assertEquals("lsp shutdown", failure.getMessage()); } diff --git a/prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java b/prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java new file mode 100644 index 00000000..be3447f8 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java @@ -0,0 +1,37 @@ +package p.studio.core.support; + +import p.studio.api.operation.*; +import java.time.Instant; +import java.util.concurrent.*; +import java.util.function.Consumer; + +/** Cancellation acknowledgement and worker termination are deliberately independent. */ +public final class ControlledOperations implements OperationExecutor { + public Handle last; + @Override public OperationHandle submit(String summary, Callable work) { + Handle handle = new Handle<>(summary, work); + last = handle; + return handle; + } + public static final class Handle implements OperationHandle { + public final CompletableFuture completed = new CompletableFuture<>(); + public final CompletableFuture stopped = new CompletableFuture<>(); + public boolean cancelled; + private final Callable work; + private final String summary; + private final OperationId id = new OperationId(java.util.UUID.randomUUID().toString()); + Handle(String summary, Callable work) { this.summary = summary; this.work = work; } + public void finish() { + try { completed.complete(work.call()); } catch (Exception failure) { completed.completeExceptionally(failure); } + stopped.complete(null); + } + @Override public OperationId id() { return id; } + @Override public OperationSnapshot snapshot() { + return new OperationSnapshot(id, cancelled ? OperationState.CANCELLED : completed.isDone() ? OperationState.SUCCEEDED : OperationState.RUNNING, Instant.now(), summary); + } + @Override public CompletionStage completion() { return completed; } + @Override public CompletionStage termination() { return stopped; } + @Override public boolean cancel() { cancelled = true; return true; } + @Override public OperationSubscription subscribe(Consumer observer) { observer.accept(snapshot()); return () -> {}; } + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java index 26a8172c..e92a0721 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java @@ -16,6 +16,22 @@ public abstract class StudioFormSection extends StudioSection { private final VBox contentHost = new VBox(); private boolean editAllowed = true; private VBox mountedSection; + private java.util.concurrent.CompletableFuture handoffSave; + + public final boolean hasUnsavedDraft() { return isDirty(); } + public final java.util.concurrent.CompletionStage saveForHandoff() { + if (!isDirty()) return java.util.concurrent.CompletableFuture.completedFuture(null); + if (handoffSave != null && !handoffSave.isDone()) return handoffSave; + handoffSave = new java.util.concurrent.CompletableFuture<>(); + try { apply(); } catch (RuntimeException failure) { handoffSave.completeExceptionally(failure); } + return handoffSave; + } + protected final void finishHandoffSave(boolean success, String message) { + if (handoffSave == null) return; + if (success) handoffSave.complete(null); + else handoffSave.completeExceptionally(new IllegalStateException(Objects.requireNonNullElse(message, "Save failed"))); + } + public final void discardDraftForHandoff() { cancel(); renderSection(); } protected StudioFormSection(I18nService i18n) { super(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java index a067142e..b6926533 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java @@ -3,6 +3,13 @@ package p.studio.ui.javafx.utilities.i18n; import lombok.Getter; public enum I18n { + WORKSPACE_DEV("workspace.dev"), + DEV_GRANT("dev.grant"), DEV_RECLAIM("dev.reclaim"), DEV_COPY_CONFIG("dev.copyConfig"), + DEV_MCP_UNAVAILABLE("dev.mcpUnavailable"), DEV_EXTERNAL_WARNING("dev.externalWarning"), + DEV_MANUAL("dev.manual"), DEV_WAITING("dev.waiting"), DEV_WORKING("dev.working"), DEV_RETURNING("dev.returning"), + DEV_SAVE_GRANT("dev.saveGrant"), DEV_UNSAVED("dev.unsaved"), + DEV_DIAGNOSTICS("dev.diagnostics"), DEV_HISTORY("dev.history"), + DEV_NO_FRAME("dev.noFrame"), DEV_STALE_FRAME("dev.staleFrame"), DEV_CURRENT_FRAME("dev.currentFrame"), APP_TITLE("app.title"), APP_PROJECT_TITLE("app.projectTitle"), SHIELD_LOADING_PROJECT("shield.loadingProject"), diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java index f4f3780e..9600f564 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java @@ -44,6 +44,9 @@ public final class MainView extends BorderPane { private final ExecutionController playStopCoordinator; private boolean initializing; private boolean workspaceLifecycleInitialized; + private p.studio.api.operation.OperationSubscription controlSubscription; + private p.studio.api.operation.OperationSubscription documentRegistration; + private boolean closed; public MainView(final ProjectSession projectSession, final Shipper shipper, final ExecutionControllerFactory executionControllerFactory, @@ -93,12 +96,29 @@ public final class MainView extends BorderPane { assetWorkspace.restoreProjectLocalState(persistedState); assetWorkspace.setStateChangedAction(this::persistProjectLocalState); host.register(new DebugWorkspace(projectReference, projectSession.executionSession(), i18n, eventBus)); - host.register(new ShipperWorkspace(projectReference, shipper, i18n, eventBus)); + final var shipperWorkspace = new ShipperWorkspace(projectReference, shipper, i18n, eventBus); + host.register(shipperWorkspace); + host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus)); + documentRegistration = projectSession.automation().registerDocuments(assetWorkspace.documentHandoff()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(assetWorkspace.rootNode(), + () -> projectSession.automation().snapshot().manualAllowed()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(shipperWorkspace.rootNode(), + () -> projectSession.automation().snapshot().manualAllowed()); + controlSubscription = projectSession.automation().subscribe(snapshot -> { + Runnable update = () -> { + if (closed) return; + runSurface.setDisable(!snapshot.manualAllowed()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.project(assetWorkspace.rootNode(), snapshot.manualAllowed()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.project(shipperWorkspace.rootNode(), snapshot.manualAllowed()); + }; + if (javafx.application.Platform.isFxApplicationThread()) update.run(); else javafx.application.Platform.runLater(update); + }); workspaceRail = new StudioWorkspaceRailControl<>( List.of( new StudioWorkspaceRailItem<>(WorkspaceId.ASSETS, "📦", i18n.bind(I18n.WORKSPACE_ASSETS)), new StudioWorkspaceRailItem<>(WorkspaceId.DEBUG, "🎮", i18n.bind(I18n.WORKSPACE_DEBUG)), + new StudioWorkspaceRailItem<>(WorkspaceId.DEV, "◇", i18n.bind(I18n.WORKSPACE_DEV)), new StudioWorkspaceRailItem<>(WorkspaceId.SHIPPER, "⚙️", i18n.bind(I18n.WORKSPACE_SHIPPER)) ), this::loadWorkspace); @@ -141,6 +161,10 @@ public final class MainView extends BorderPane { } public void close() { + if (closed) return; + closed = true; + controlSubscription.unsubscribe(); + documentRegistration.unsubscribe(); playStopCoordinator.shutdown(); persistProjectLocalState(); host.deactivateCurrentWorkspace(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java index 58383dad..b1896e25 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java @@ -11,15 +11,18 @@ import java.util.List; import java.util.Objects; public final class StudioWorkspaceLifecycleSupport { + private static final Object ACTIVATION = new Object(); private StudioWorkspaceLifecycleSupport() { } public static void activate(Workspace workspace) { final Workspace target = Objects.requireNonNull(workspace, "workspace"); final Node rootNode = target.rootNode(); + final Object activation = new Object(); + rootNode.getProperties().put(ACTIVATION, activation); final Scene scene = rootNode.getScene(); if (scene != null) { - activateNow(target); + activateNow(target, activation); return; } @@ -33,13 +36,14 @@ public final class StudioWorkspaceLifecycleSupport { return; } rootNode.sceneProperty().removeListener(this); - activateNow(target); + activateNow(target, activation); } }); } public static void deactivate(Workspace workspace) { final Workspace target = Objects.requireNonNull(workspace, "workspace"); + target.rootNode().getProperties().remove(ACTIVATION); target.unLoad(); final List participants = target.lifecycleParticipants(); for (int index = participants.size() - 1; index >= 0; index--) { @@ -47,8 +51,9 @@ public final class StudioWorkspaceLifecycleSupport { } } - private static void activateNow(Workspace workspace) { + private static void activateNow(Workspace workspace, Object activation) { Platform.runLater(() -> { + if (workspace.rootNode().getProperties().get(ACTIVATION) != activation) return; final List participants = workspace.lifecycleParticipants(); for (StudioControlLifecycle participant : participants) { participant.subscribe(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java index 3d346af8..7a2337fd 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java @@ -3,5 +3,6 @@ package p.studio.ui.javafx.workspaces; public enum WorkspaceId { ASSETS, SHIPPER, - DEBUG + DEBUG, + DEV } diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java index 02f742bf..d4d8cb3b 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java @@ -126,6 +126,8 @@ public final class AssetWorkspace extends Workspace { this.stateChangedAction = java.util.Objects.requireNonNull(stateChangedAction, "stateChangedAction"); } + public p.studio.api.automation.DocumentHandoff documentHandoff() { return detailsControl.documentHandoff(); } + public void restoreProjectLocalState(final ProjectLocalStudioState projectLocalStudioState) { pendingAssetsLayoutState = projectLocalStudioState.shellLayout().assetsLayout(); reapplyPendingLayoutState(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java index e4fb5dae..533fff0d 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java @@ -85,6 +85,63 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware private boolean actionRunning; private String actionFeedbackMessage; + public p.studio.api.automation.DocumentHandoff documentHandoff() { + return new p.studio.api.automation.DocumentHandoff() { + private volatile boolean disposed; + private final java.util.Set> pending = java.util.concurrent.ConcurrentHashMap.newKeySet(); + @Override public void close() { + disposed = true; + pending.forEach(future -> future.complete(null)); + pending.clear(); + } + @Override public java.util.concurrent.CompletionStage hasUnsavedChanges() { + return onFx(() -> handoffForms().stream().anyMatch(p.studio.ui.javafx.controls.forms.StudioFormSection::hasUnsavedDraft)); + } + @Override public java.util.concurrent.CompletionStage saveAll() { + return onFx(() -> { + java.util.concurrent.CompletionStage saved = java.util.concurrent.CompletableFuture.completedFuture(null); + for (var form : handoffForms()) saved = saved.thenCompose(v -> form.saveForHandoff()); + return saved; + }).thenCompose(saved -> saved); + } + @Override public java.util.concurrent.CompletionStage refreshFromDisk() { + var refreshed = new java.util.concurrent.CompletableFuture(); + pending.add(refreshed); + refreshed.whenComplete((v, f) -> pending.remove(refreshed)); + if (disposed) { refreshed.complete(null); return refreshed; } + onFx(() -> { + if (disposed) { refreshed.complete(null); return null; } + handoffForms().forEach(p.studio.ui.javafx.controls.forms.StudioFormSection::discardDraftForHandoff); + var selected = viewState.selectedAssetReference(); + if (selected == null) { refreshed.complete(null); return refreshed; } + long generation = loadGeneration.incrementAndGet(); + executor.execute(() -> { + try { + var details = mapDetails(assetDetails.get(projectReference, selected)); + Platform.runLater(() -> { if (!disposed) applyLoadedDetails(generation, selected, details); refreshed.complete(null); }); + } catch (RuntimeException failure) { + Platform.runLater(() -> { if (!disposed) applyLoadFailure(generation, selected, failure); refreshed.completeExceptionally(failure); }); + } + }); + return refreshed; + }).whenComplete((v, failure) -> { if (failure != null) refreshed.completeExceptionally(failure); }); + return refreshed; + } + }; + } + + private java.util.List handoffForms() { + var forms = new java.util.ArrayList<>(contractControl.handoffForms()); + forms.add(bankCompositionControl); forms.add(colorSchemaGroupsControl); forms.add(paletteOverhaulingControl); + return forms; + } + private static java.util.concurrent.CompletableFuture onFx(java.util.function.Supplier action) { + var result = new java.util.concurrent.CompletableFuture(); + Runnable run = () -> { try { result.complete(action.get()); } catch (RuntimeException f) { result.completeExceptionally(f); } }; + if (Platform.isFxApplicationThread()) run.run(); else Platform.runLater(run); + return result; + } + public AssetDetailsControl( ProjectReference projectReference, StudioWorkspaceEventBus workspaceBus, @@ -382,6 +439,7 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware AssetDetailsUiSupport.applyActionTone(analyseButton, "studio-button-warning"); analyseButton.setDisable(actionRunning || viewState.selectedAssetDetails().diagnostics().isEmpty()); analyseButton.setOnAction(ignored -> openDiagnosticsDialog()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(analyseButton); nodes.add(analyseButton); if (canGenerateTsx()) { final Button exportTsxButton = AssetDetailsUiSupport.createActionButton(i18n.text(I18n.ASSETS_ACTION_EXPORT_TSX)); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java index 97866226..7504b2b0 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java @@ -212,16 +212,20 @@ public final class AssetDetailsBankCompositionControl extends StudioFormSection final var response = assetCommands.applyBankComposition(projectReference, assetReference, selectedPaths); Platform.runLater(() -> { if (response.success()) { + coordinator.apply(); publishEditScope(workspaceBus, currentScopeKey(), null); + finishHandoffSave(true, ""); workspaceBus.publish(new StudioAssetBankCompositionAppliedEvent(assetReference)); executor.execute(() -> publishAppliedBankComposition(assetReference)); } else { + finishHandoffSave(false, response.errorMessage()); workspaceBus.publish(new StudioAssetBankCompositionApplyFailedEvent( assetReference, response.errorMessage())); } }); } catch (Exception exception) { + Platform.runLater(() -> finishHandoffSave(false, exception.getMessage())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetBankCompositionApplyFailedEvent( assetReference, "Unable to apply bank composition."))); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java index 86f0372a..fb7a4a9a 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java @@ -48,6 +48,8 @@ public final class AssetDetailsContractControl extends HBox implements StudioCon private AssetWorkspaceDetailsViewState viewState; + public java.util.List handoffForms() { return java.util.List.of(runtimeSection, codecSection); } + public AssetDetailsContractControl(ProjectReference projectReference, StudioWorkspaceEventBus workspaceBus, p.studio.ui.javafx.utilities.i18n.I18nService i18n, java.util.concurrent.Executor executor, AssetCommands assetCommands) { @@ -283,14 +285,15 @@ public final class AssetDetailsContractControl extends HBox implements StudioCon private void handleApplyResponse(boolean success, String errorMessage) { if (success) { formSession().apply(); + finishHandoffSave(true, ""); publishEditScope(workspaceBus, currentScopeKey(), null); logContractEvent("Runtime contract updated"); requestRefresh(); renderSection(); return; } + finishHandoffSave(false, errorMessage); logContractEvent(errorMessage); - cancel(); renderSection(); } @@ -447,14 +450,15 @@ public final class AssetDetailsContractControl extends HBox implements StudioCon private void handleApplyResponse(boolean success, String errorMessage) { if (success) { formSession().apply(); + finishHandoffSave(true, ""); publishEditScope(workspaceBus, currentScopeKey(), null); logContractEvent("Codec updated"); requestRefresh(); renderSection(); return; } + finishHandoffSave(false, errorMessage); logContractEvent(errorMessage); - cancel(); renderSection(); } diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java index b5aeeb15..1bd8bcc9 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java @@ -223,6 +223,7 @@ public final class AssetDetailsPaletteOverhaulingControl extends StudioFormSecti .filter(Objects::nonNull) .toList(); if (selectedPalettes.isEmpty()) { + finishHandoffSave(false, "No palette selected"); workspaceBus.publish(new StudioAssetLogEvent("palette-overhauling", "Apply failed: no palette was selected.")); workspaceBus.publish(new StudioPackerOperationEvent( UUID.randomUUID().toString(), @@ -240,15 +241,18 @@ public final class AssetDetailsPaletteOverhaulingControl extends StudioFormSecti Platform.runLater(() -> { if (response.success()) { coordinator.apply(); + finishHandoffSave(true, ""); publishEditScope(workspaceBus, currentScopeKey(), null); renderSection(); workspaceBus.publish(new StudioAssetsWorkspaceSelectionRequestedEvent(assetReference, true)); } else { + finishHandoffSave(false, response.errorMessage()); workspaceBus.publish(new StudioAssetLogEvent("palette-overhauling", "Apply failed: " + Objects.requireNonNullElse(response.errorMessage(), "unknown error"))); } }); } catch (Exception exception) { + Platform.runLater(() -> finishHandoffSave(false, exception.getMessage())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetLogEvent( "palette-overhauling", "Apply failed due to an unexpected error."))); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java index 05e2042d..799eac40 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java @@ -181,16 +181,19 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio } final AssetColorSchemaState draft = coordinator.state(); if (!draft.selected()) { + finishHandoffSave(false, "Select or create a schema first"); workspaceBus.publish(new StudioAssetLogEvent("color-schema-groups", "Apply failed: select or create a schema first.")); return; } if (!draft.removeRequested()) { final List orderedColors = draft.orderedColors(); if (draft.assignedTiles().isEmpty() || orderedColors.isEmpty()) { + finishHandoffSave(false, "Schema requires at least one tile"); workspaceBus.publish(new StudioAssetLogEvent("color-schema-groups", "Apply failed: schema must contain at least one tile.")); return; } if (orderedColors.size() > 16) { + finishHandoffSave(false, "Schema exceeds palette capacity"); workspaceBus.publish(new StudioAssetLogEvent( "color-schema-groups", i18n.text(I18n.ASSETS_COLOR_SCHEMA_DIALOG_TOO_MANY_COLORS))); @@ -207,6 +210,7 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio : coordinator.upsertSchema(draft.schemaId(), draft.assignedTiles(), draft.orderedColors()); final var writeResult = metadataService.writeGlyphMaterialMetadata(assetDetails.summary().assetRoot(), metadata); if (!writeResult.successful()) { + Platform.runLater(() -> finishHandoffSave(false, writeResult.message())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetLogEvent( "color-schema-groups", "Unable to save schema: " + writeResult.message()))); @@ -214,6 +218,7 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio } Platform.runLater(() -> { coordinator.apply(); + finishHandoffSave(true, ""); selectedSchemaId = draft.removeRequested() ? null : draft.schemaId(); publishEditScope(workspaceBus, currentScopeKey(), null); workspaceBus.publish(new StudioAssetLogEvent( @@ -223,6 +228,7 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio renderSection(); }); } catch (RuntimeException exception) { + Platform.runLater(() -> finishHandoffSave(false, exception.getMessage())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetLogEvent( "color-schema-groups", "Unable to save schema."))); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java index 7d03ad22..d474cbc7 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java @@ -98,6 +98,7 @@ public final class AssetListControl extends VBox implements StudioEventAware { } private TextField createSearchField() { + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(searchField); searchField.setPromptText(i18n.text(I18n.ASSETS_SEARCH_PROMPT)); searchField.getStyleClass().add("assets-workspace-search"); return searchField; @@ -117,6 +118,7 @@ public final class AssetListControl extends VBox implements StudioEventAware { } private ToggleButton configureFilterButton(ToggleButton button, I18n i18n) { + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(button); button.textProperty().bind(this.i18n.bind(i18n)); button.getStyleClass().addAll("studio-button", "studio-button-secondary", "studio-button-pill", "studio-button-toggle"); return button; diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java new file mode 100644 index 00000000..05810691 --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java @@ -0,0 +1,108 @@ +package p.studio.ui.javafx.workspaces.dev; + +import javafx.application.Platform; +import javafx.geometry.Insets; +import javafx.scene.Node; +import javafx.scene.control.*; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.*; +import p.studio.api.automation.*; +import p.studio.api.operation.OperationSubscription; +import p.studio.api.project.ProjectReference; +import p.studio.ui.javafx.events.StudioEventBus; +import p.studio.ui.javafx.utilities.i18n.*; +import p.studio.ui.javafx.workspaces.*; +import java.io.ByteArrayInputStream; + +/** Human authorization and observation only; never an embedded agent or a fake runtime. */ +public final class DevWorkspace extends Workspace { + private final VBox root = new VBox(12); + private final ScrollPane scroll = new ScrollPane(root); + private final AutomationSession automation; + private final I18nService i18n; + private final Label state = new Label(), identity = new Label(), operation = new Label(), imageStatus = new Label(); + private final TextArea diagnostics = new TextArea(), history = new TextArea(); + private final ImageView canvas = new ImageView(); + private final Button grant = new Button(), reclaim = new Button(); + private OperationSubscription subscription; + private long generation; + private CanonicalCapture rendered; + private final javafx.beans.value.ChangeListener localeListener; + + public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events) { + super(project, events); this.automation = automation; this.i18n = i18n; + localeListener = (o, before, after) -> apply(this.automation.snapshot()); + scroll.setFitToWidth(true); + root.setPadding(new Insets(16)); root.getStyleClass().add("dev-workspace"); + grant.setId("dev-grant"); reclaim.setId("dev-reclaim"); + grant.textProperty().bind(i18n.bind(I18n.DEV_GRANT)); + reclaim.textProperty().bind(i18n.bind(I18n.DEV_RECLAIM)); + grant.setOnAction(e -> grant(false)); + reclaim.setOnAction(e -> automation.reclaim()); + Button configuration = new Button(); configuration.setId("dev-mcp-config"); + configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); configuration.setDisable(true); + Label availability = new Label(); availability.textProperty().bind(i18n.bind(I18n.DEV_MCP_UNAVAILABLE)); + Label warning = new Label(); warning.setWrapText(true); + warning.textProperty().bind(i18n.bind(I18n.DEV_EXTERNAL_WARNING)); + canvas.setPreserveRatio(true); canvas.setSmooth(false); canvas.setFitWidth(640); canvas.setFitHeight(360); + StackPane imagePane = new StackPane(canvas); imagePane.setMinHeight(200); imagePane.getStyleClass().add("dev-canvas"); + diagnostics.setEditable(false); diagnostics.setPrefRowCount(3); + history.setEditable(false); history.setPrefRowCount(5); + root.getChildren().addAll(new Label(project.name() + " — " + project.rootPath()), + state, new HBox(10, grant, reclaim, configuration), availability, warning, + operation, imageStatus, imagePane, identity, + pane(I18n.DEV_DIAGNOSTICS, diagnostics), pane(I18n.DEV_HISTORY, history)); + apply(automation.snapshot()); + } + + private TitledPane pane(I18n key, Node content) { + TitledPane pane = new TitledPane(); pane.textProperty().bind(i18n.bind(key)); + pane.setContent(content); pane.setCollapsible(false); return pane; + } + @Override public WorkspaceId workspaceId() { return WorkspaceId.DEV; } + @Override public I18n title() { return I18n.WORKSPACE_DEV; } + @Override public Node rootNode() { return scroll; } + @Override public void load() { + if (subscription != null) return; + i18n.localeProperty().addListener(localeListener); + long subscribed = ++generation; + subscription = automation.subscribe(snapshot -> { + Runnable update = () -> { if (generation == subscribed) apply(snapshot); }; + if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); + }); + } + @Override public void unLoad() { + generation++; + i18n.localeProperty().removeListener(localeListener); + if (subscription != null) { subscription.unsubscribe(); subscription = null; } + } + private void grant(boolean save) { + automation.grant(save).whenComplete((result, failure) -> Platform.runLater(() -> { + if (failure != null) { diagnostics.setText(failure.getMessage()); return; } + if (result.status() == ControlResult.Status.DIRTY_DOCUMENTS) { + ButtonType confirm = new ButtonType(i18n.text(I18n.DEV_SAVE_GRANT), ButtonBar.ButtonData.OK_DONE); + Alert dialog = new Alert(Alert.AlertType.CONFIRMATION, i18n.text(I18n.DEV_UNSAVED), confirm, ButtonType.CANCEL); + if (root.getScene() != null) dialog.initOwner(root.getScene().getWindow()); + if (dialog.showAndWait().orElse(ButtonType.CANCEL) == confirm) grant(true); + } + })); + } + private void apply(AutomationSnapshot snapshot) { + var view = DevWorkspaceProjection.from(snapshot); + state.setText(i18n.text(switch (view.state()) { + case MANUAL -> I18n.DEV_MANUAL; + case WAITING_FOR_AGENT -> I18n.DEV_WAITING; + case AGENT_WORKING -> I18n.DEV_WORKING; + case RETURNING_CONTROL -> I18n.DEV_RETURNING; + })); + grant.setDisable(!view.grantEnabled()); reclaim.setDisable(!view.reclaimEnabled()); + identity.setText(view.identity()); operation.setText(view.operation()); + diagnostics.setText(view.diagnostics()); history.setText(view.calls()); + imageStatus.setText(i18n.text(view.capture() == null ? I18n.DEV_NO_FRAME : view.stale() ? I18n.DEV_STALE_FRAME : I18n.DEV_CURRENT_FRAME)); + if (rendered != view.capture()) { + rendered = view.capture(); + canvas.setImage(rendered == null ? null : new Image(new ByteArrayInputStream(rendered.png()))); + } + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java new file mode 100644 index 00000000..b4c149cf --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java @@ -0,0 +1,16 @@ +package p.studio.ui.javafx.workspaces.dev; + +import p.studio.api.automation.*; + +public record DevWorkspaceProjection(ControlState state, boolean grantEnabled, boolean reclaimEnabled, + boolean stale, CanonicalCapture capture, String identity, String operation, String diagnostics, String calls) { + public static DevWorkspaceProjection from(AutomationSnapshot s) { + var frame = s.capture(); + String identity = frame == null ? "" : "session=" + frame.sessionId() + " | build=" + frame.buildId() + + " | logical=" + frame.logicalFrameIndex() + " | FrameId=" + frame.frameId() + + " | " + frame.width() + "×" + frame.height() + " | stride=" + frame.stridePixels(); + return new DevWorkspaceProjection(s.state(), s.canGrant(), s.canReclaim(), s.stale(), frame, identity, + s.operation() == null ? "" : s.operation().id().value() + " | " + s.operation().state() + " | " + s.operation().summary(), + String.join("\n", s.diagnostics()), String.join("\n", s.calls())); + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java new file mode 100644 index 00000000..669e6d9f --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java @@ -0,0 +1,48 @@ +package p.studio.ui.javafx.workspaces.dev; + +import javafx.event.ActionEvent; +import javafx.scene.Node; +import javafx.scene.control.ButtonBase; +import javafx.scene.control.TextInputControl; +import javafx.scene.input.KeyEvent; +import javafx.scene.input.MouseEvent; +import javafx.css.PseudoClass; +import java.util.function.BooleanSupplier; + +/** Presentation guard only. Core service admission remains authoritative. */ +public final class ManualProjectUiGuard { + public static final String READ_ONLY_ACTION = "studio.readOnlyAction"; + private ManualProjectUiGuard() { } + public static void allowReadOnly(Node node) { + node.getProperties().put(READ_ONLY_ACTION, true); + node.getStyleClass().add("studio-read-only-action"); + } + public static void install(Node root, BooleanSupplier manualAllowed) { + root.addEventFilter(ActionEvent.ACTION, event -> { + if (!manualAllowed.getAsBoolean() && event.getTarget() instanceof Node target + && !Boolean.TRUE.equals(target.getProperties().get(READ_ONLY_ACTION))) event.consume(); + }); + root.addEventFilter(KeyEvent.KEY_TYPED, event -> { + if (!manualAllowed.getAsBoolean() && mutationTarget(event.getTarget())) event.consume(); + }); + root.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> { + if (!manualAllowed.getAsBoolean() && mutationTarget(event.getTarget())) event.consume(); + }); + root.addEventFilter(KeyEvent.KEY_PRESSED, event -> { + if (!manualAllowed.getAsBoolean() && mutationTarget(event.getTarget())) event.consume(); + }); + } + public static void project(Node root, boolean manualAllowed) { + root.pseudoClassStateChanged(PseudoClass.getPseudoClass("automation-locked"), !manualAllowed); + } + private static boolean mutationTarget(Object target) { + Node node = target instanceof Node value ? value : null; + while (node != null) { + if (Boolean.TRUE.equals(node.getProperties().get(READ_ONLY_ACTION))) return false; + if (node instanceof ButtonBase || node instanceof javafx.scene.control.ComboBoxBase + || node instanceof TextInputControl text && text.isEditable()) return true; + node = node.getParent(); + } + return false; + } +} diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties index 7184af4a..6ee9a196 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties @@ -357,3 +357,20 @@ assets.packWizard.error.deepSync=Unable to complete deep sync for the current wo assets.packWizard.error.validation=Unable to validate the current pack set. assets.packWizard.error.pack=Unable to pack the current build set. workspace.debug=Debug +workspace.dev=DEV +dev.grant=Grant control to AI +dev.reclaim=Interrupt and reclaim control +dev.copyConfig=Copy MCP configuration +dev.mcpUnavailable=MCP connection is not available yet. This stage provides project control and observation. +dev.externalWarning=Reclaiming control stops Studio-managed work, not direct writes by your external agent. Stop that client separately. Existing edits are preserved. +dev.manual=Manual control +dev.waiting=Waiting for agent — project control granted +dev.working=Agent working — task acquired +dev.returning=Returning control — stopping work and refreshing documents +dev.saveGrant=Save all and grant +dev.unsaved=Studio has unsaved changes. Save all before granting project control? +dev.diagnostics=Diagnostics +dev.history=Recent Studio calls +dev.noFrame=No runtime capture +dev.staleFrame=Stale capture — previous build or execution +dev.currentFrame=Canonical runtime capture diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties index 5e00b3ed..ff673d74 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties @@ -28,3 +28,20 @@ workspace.debug.status.connecting=Conectando workspace.debug.status.running=Executando workspace.debug.status.runtimeFailed=Runtime falhou workspace.debug.status.stopped=Parado +workspace.dev=DEV +dev.grant=Ceder controle à IA +dev.reclaim=Interromper e retomar controle +dev.copyConfig=Copiar configuração MCP +dev.mcpUnavailable=A conexão MCP ainda não está disponível. Esta etapa oferece controle do projeto e acompanhamento. +dev.externalWarning=Retomar controle encerra o trabalho gerenciado pelo Studio, não as escritas diretas do agente externo. Pare esse cliente separadamente. As alterações existentes são preservadas. +dev.manual=Controle manual +dev.waiting=Aguardando agente — controle do projeto cedido +dev.working=Agente trabalhando — tarefa adquirida +dev.returning=Retomando controle — encerrando trabalho e atualizando documentos +dev.saveGrant=Salvar tudo e ceder +dev.unsaved=Existem alterações não salvas no Studio. Salvar tudo antes de ceder o controle? +dev.diagnostics=Diagnósticos +dev.history=Chamadas recentes ao Studio +dev.noFrame=Nenhuma captura do runtime +dev.staleFrame=Captura desatualizada — build ou execução anterior +dev.currentFrame=Captura canônica do runtime diff --git a/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css b/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css index c98780ff..f5c479ad 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css +++ b/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css @@ -1583,3 +1583,8 @@ -fx-text-fill: #b9cae0; -fx-font-size: 12px; } +.dev-canvas { -fx-background-color: #16191f; -fx-padding: 12; } +.automation-locked { -fx-opacity: 0.95; } +.assets-workspace:automation-locked .button, +.shipper-workspace:automation-locked .button { -fx-opacity: 0.45; } +.assets-workspace:automation-locked .studio-read-only-action { -fx-opacity: 1; } diff --git a/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java b/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java new file mode 100644 index 00000000..cf26fa4c --- /dev/null +++ b/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java @@ -0,0 +1,31 @@ +package p.studio.ui.javafx.workspaces.dev; + +import org.junit.jupiter.api.Test; +import p.studio.api.automation.*; +import java.nio.file.Path; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +class DevWorkspaceProjectionTest { + @Test void actionMappingUsesAuthorityAndNeverInventsAnEndpointOrFrame() { + for (var state : ControlState.values()) { + var view = DevWorkspaceProjection.from(snapshot(state, null, false, false)); + assertEquals(state == ControlState.MANUAL, view.grantEnabled()); + assertEquals(state != ControlState.MANUAL, view.reclaimEnabled()); + assertNull(view.capture()); assertEquals("", view.identity()); + } + var closed = DevWorkspaceProjection.from(snapshot(ControlState.MANUAL, null, false, true)); + assertFalse(closed.grantEnabled()); assertFalse(closed.reclaimEnabled()); + } + @Test void captureIdentityRetainsIndependentLogicalAndRenderCountersAndStaleness() { + var frame = new CanonicalCapture("session-A", "build-B", 99, 7, 320, 180, 320, new byte[]{1}); + var view = DevWorkspaceProjection.from(snapshot(ControlState.AGENT_WORKING, frame, true, false)); + assertSame(frame, view.capture()); assertTrue(view.stale()); + assertTrue(view.identity().contains("logical=99")); assertTrue(view.identity().contains("FrameId=7")); + assertTrue(view.identity().contains("session-A")); assertTrue(view.identity().contains("build-B")); + assertEquals("diagnostic", view.diagnostics()); assertEquals("call", view.calls()); + } + private AutomationSnapshot snapshot(ControlState state, CanonicalCapture frame, boolean stale, boolean closed) { + return new AutomationSnapshot(Path.of("."), state, false, closed, 0, null, null, frame, stale, List.of("diagnostic"), List.of("call")); + } +} From 9f61f9c07dfa4c7c07c9b16083f53c7056ac3238 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 07:55:29 +0100 Subject: [PATCH 02/15] add MCP tool contracts and authenticated local HTTP transport --- .../10. DEV and Automation Specification.md | 3 + ...CP Tools and Project Knowledge Contract.md | 216 ++ docs/specs/studio/README.md | 4 +- .../app/StudioApplicationConfiguration.java | 16 + .../java/p/studio/app/mcp/ContractSchema.java | 48 + .../java/p/studio/app/mcp/LocalMcpServer.java | 203 ++ .../java/p/studio/app/mcp/McpToolCatalog.java | 39 + .../p/studio/app/mcp/McpToolRegistry.java | 40 + .../java/p/studio/app/mcp/McpToolResult.java | 41 + .../main/resources/mcp/studio-tools-v1.json | 1784 +++++++++++++++++ .../StudioApplicationConfigurationTest.java | 4 + .../p/studio/app/mcp/LocalMcpServerTest.java | 133 ++ .../p/studio/app/mcp/McpContractTest.java | 81 + .../architecture/StudioBoundaryArchTest.java | 7 + .../api/automation/AutomationFailure.java | 15 + .../api/automation/OperationLookup.java | 11 + .../api/automation/ProjectKnowledge.java | 63 + .../api/automation/TrackedOperation.java | 23 + 18 files changed, 2730 insertions(+), 1 deletion(-) create mode 100644 docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpToolResult.java create mode 100644 prometeu-app/src/main/resources/mcp/studio-tools-v1.json create mode 100644 prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/OperationLookup.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectKnowledge.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/TrackedOperation.java diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md index a256fdb8..bf1dcfef 100644 --- a/docs/specs/studio/10. DEV and Automation Specification.md +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -239,6 +239,9 @@ that it uses. Capture/build correlation MUST NOT introduce code snapshots. ## 8. Local MCP Admission and Functional Surface +Concrete tool names, input schemas, response envelopes and HTTP lifecycle are +specified in [MCP Tools and Project Knowledge Contract](11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md). + The app MUST host Streamable HTTP at `127.0.0.1:/mcp` while Studio is open. It MUST generate a random token per Studio start, require it on connections, validate Origin and reject unexpected origins. No remote 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 new file mode 100644 index 00000000..ffc75335 --- /dev/null +++ b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md @@ -0,0 +1,216 @@ +# MCP Tools and Project Knowledge Contract + +## Status, Scope and Authority + +Owner: **studio**, application adapter and neutral automation API. This document +formalizes DEC-0060 B5–B9 and PLN-0139 steps 15–16. It complements +[DEV and Automation](10.%20DEV%20and%20Automation%20Specification.md), which owns +project authority, lifecycle, captures and phase gates. It does not change those +rules or the runtime-owned headless protocol. + +The packaged machine-readable input schemas, authority classification and +examples are in `prometeu-app/src/main/resources/mcp/studio-tools-v1.json`. +Contract version is `1.0`. Catalog membership is not runtime availability: +`tools/list` MUST expose only composed handlers, never placeholder implementations. +Steps 17–21 connect the functional providers and DEV configuration assistance; +steps 22–28 provide the real runtime gateway and integrated acceptance. + +## 1. Connection Contract + +The app hosts `/mcp` on **127.0.0.1 with an OS-assigned port**, using the JSON +response form of MCP Streamable HTTP, protocol revision `2025-06-18`. The +initialization exchange negotiates that supported revision; no compatibility +with other revisions or deprecated HTTP+SSE transport is claimed. An offered +unsupported revision receives the supported revision in `InitializeResult`. + +Each start generates a fresh 256-bit random bearer token. Every request MUST +include `Authorization: Bearer `. Missing/wrong credentials return 401. +There is no query-string token, OAuth, cookie authentication, remote bind option, +stdio bridge or wildcard listener. The endpoint has no query parameters. + +Native clients may omit `Origin`. If present, it MUST exactly equal the live +endpoint's origin (`http://127.0.0.1:`); `null`, other ports/hosts/schemes +and multiple Origin headers fail. Host MUST match the live loopback authority. +Unexpected origins/hosts return 403. No permissive browser CORS policy is emitted. +Credentials MUST NOT appear in diagnostics, exception messages, object string +representations, generated reports or versioned configuration. Explicit copying +for the external client is provided in step 21, not by logging startup secrets. + +Initialization assigns a separate random `Mcp-Session-Id`. Subsequent requests +include this header and the negotiated `MCP-Protocol-Version`. The server can +recover the negotiated version from its connection session if the version header +is absent; an explicitly unsupported header returns 400. Missing required +session returns 400; an unknown/closed session returns 404. The client sends +`notifications/initialized` before tools. `ping` is available after initialization. + +POST requires UTF-8 JSON and Accept support for `application/json` and +`text/event-stream`. Responses use JSON, not SSE. GET returns 405. DELETE closes +only the connection session, not project authority. Accepted notifications and +client responses return 202 without a body. Notification/disconnection alone +MUST NOT revoke a task or cancel an operation already returned by operationId. + +The transport bounds incoming bodies to 1 MiB, sessions to 128 and request +handling to a bounded worker queue. Oversized bodies return 413; exhausted +session capacity returns 503. Stalled exchanges close after 15 seconds. These +are HTTP resource protections, **not** task expiration or guest/runtime timeouts. +Build/advance MUST return operation identities promptly. A lost response is +resolved by authorized lookup, not by assuming cancellation or replay. + +These details follow the official MCP [transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports), +[lifecycle](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle) +and [tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools) +contracts. Optional SSE, server-initiated requests, sampling, prompts, resource +subscriptions and list-change notifications are not advertised. + +## 2. Identity and Admission + +All tool inputs require `projectRoot`: an absolute filesystem root resolving to +an open project. UI focus never supplies it. Core services resolve the actual +project, including canonical-path/scope checks; syntactic validation does not +prove authorization. + +The authority levels in the packaged catalog are: + +- `authenticated`: connection authentication only; project/context/reference reads + are allowed before grant. No task token is returned by discovery. +- `granted`: acquisition validates the prior human grant and atomically creates + the sole task identity. The transport session ID is not that identity. +- `task`: `projectRoot` and `taskId` must identify the current acquired task. + Revalidate before admission, lookup and deduplication, including read-only LSP. + +No MCP tool grants human permission or simulates pressing the DEV button. +There are no arbitrary-file read/write, shell, Git or publication tools. Editing +uses the external client's native tools within the context's editable scope. + +## 3. v1 Tool Catalog + +Fields below supplement `projectRoot`, and `taskId` where authority is `task`. +Input objects reject undeclared fields. IDs are nonempty opaque strings. + +| Tool | Authority | Additional input | Successful value | +| --- | --- | --- | --- | +| `studio_project_context` | authenticated | none | Project context in section 5 | +| `studio_reference_read` | authenticated | referenceId; optional offset/limit | Indexed reference page | +| `studio_control_acquire` | granted | none | taskId, state=AGENT_WORKING | +| `studio_control_release` | task | none | state=MANUAL, only after ordered cleanup | +| `studio_language_query` | task | operation, parameters | Supported LSP query/proposal result | +| `studio_build_start` | task | clientRequestId | operationId, clientRequestId, state | +| `studio_headless_boot` | task | buildId | sessionId, buildId; boot uses the task's known build | +| `studio_headless_reset` | task | none | Current session/reset state | +| `studio_headless_set_input` | task | input | Current session acknowledgement | +| `studio_headless_clear_input` | task | none | Current session acknowledgement | +| `studio_headless_advance` | task | clientRequestId, frames | operationId, clientRequestId, state | +| `studio_headless_capture` | task | none | Canonical image and metadata in section 6 | +| `studio_headless_state` | task | none | Current session and runtime state | +| `studio_headless_fault` | task | none | fault object or null, preserving structural fault details | +| `studio_headless_shutdown` | task | none | Session shutdown acknowledgement after managed cleanup | +| `studio_operation_get` | task | exactly one of operationId/clientRequestId | State, known progress, typed result/failure | +| `studio_operation_cancel` | task | operationId | operationId, cancellationRequested | + +Boot MUST NOT accept an arbitrary cartridge path. The shared service resolves +buildId to known project artifacts. Runtime limits/capabilities come from the +actual runtime, not fixed MCP promises. Frames is a nonnegative integer (zero +is valid); values beyond effective limits fail rather than being clamped. + +Input is a replacement snapshot: booleans `up/down/left/right/a/b/x/y/l/r/start/ +select/touch`, signed 32-bit `touchX/touchY`. Omitted fields reset to false/zero. +It preserves the runtime's normal sampling/edge semantics, not UI keyboard events. + +Language queries use the capabilities returned by project context. Parameters +may contain URI, zero-based UTF-16 position/range/positions, workspace query, +newName, includeDeclaration or task-local itemId for multi-stage queries. The +provider MUST validate the parameters needed by the selected operation and reject +unsupported operations explicitly. Diagnostics, definitions, references and +symbols reuse the existing project LSP. Other queries/refactoring proposals are +exposed only when supported; returned edits MUST respect project versus read-only +SDK/library scope. No query applies filesystem edits. + +## 4. Result, Error and Operation Contracts + +Successful tools return `isError:false` with structuredContent +`{"status":"ok","value":{...}}`. Domain/admission failures return +`isError:true` with `{"status":"error","error":{"code":"...","message":"..."}}`. +Both include a text content block serializing the same structured data for clients +that do not render structuredContent. Clients use error codes, not parsed prose. + +`AutomationFailure.Code` defines domain codes, including project-not-open, +not-granted, invalid-task, busy, unsupported language/capability, missing +reference/documentation, out-of-scope/read-only scope, missing operation/build/ +runtime session, duplicate-ID parameter conflict, unavailable/incompatible runtime, +missing frame, exceeded limit, not-cancelable and infrastructure failure. +Unknown methods, malformed JSON-RPC and schema-invalid arguments remain protocol +errors (-32601, -32600/-32700 and -32602); unexpected internals use sanitized +-32603 responses, never request bodies, stack traces or credentials. + +Build failure and guest fault are **operation outcomes**, not implicit release. +`TrackedOperation` carries the existing `OperationSnapshot`, clientRequestId, +known progress and either the existing typed build result or runtime outcome. +Unknown requested/completed frame counts are null. Terminal infrastructure +failure/cancellation MUST preserve only known progress. Cancellation acknowledgement +does not assert worker termination or grant manual control. + +The wire receipt flattens operationId/state from the neutral operation snapshot. +Polling additionally returns progress and typed result/failure; incomplete results +are null. Build results retain diagnostics/artifact correlation. Runtime results +retain requested/completed frames and distinguish success, guest fault, +termination, cancellation and infrastructure failure. Captured results include +the same MCP image block used by direct capture. + +`clientRequestId` deduplication is task-local and in-memory. Same ID plus same +effective parameters returns the same operation; changed parameters fail with +CLIENT_REQUEST_CONFLICT. Operation lookup accepts exactly one key. Revoked, +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. + +## 5. Project Knowledge DTOs + +Neutral `ProjectKnowledge.Context` contains projectRoot/projectName, languages, +libraries, editableRoots/readOnlyRoots, indexed references and explicit limitations. +Its source is the project manifest and installed providers, never an AI-only file. + +Each language includes id/primary, separately identified languageVersion, +compilerVersion and sdkVersion, source extensions/roots, real capabilities and +reference IDs. Version has `value` and `source`; unknown value is null with +source `unknown`. Capability support distinguishes SUPPORTED/UNSUPPORTED/UNKNOWN +and can explain a limitation. Unknown declared language MUST NOT fall back to PBS. + +Libraries include identity, known version, roots and whether they belong to the +editable project. External libraries and SDK remain read-only. Reference entries +identify id/title/owner/kind/version; kinds include QUICKSTART, SYNTAX, SEMANTICS, +EXAMPLE, SDK and LIBRARY. Indexed content belongs to its language/SDK owner. + +Reference reads take an opaque ID from that index, not a path or arbitrary URI. +Offset defaults to 0; limit defaults to 4000 and accepts 1–16000 Unicode code +points. A page returns referenceId, offset, total, text and nextOffset (null at +end). Invalid pagination fails; unknown/traversal-like IDs cannot escape the +index. Installed packaging and real provider resolution are steps 17–18. + +## 6. Image Contract + +MCP image content has `type:image`, `mimeType:image/png`, and base64 `data` of +the unchanged `CanonicalCapture.png` bytes. No screenshot, log scraping, temporary +path or network fetch is required. The structured value includes sessionId, +buildId, logicalFrameIndex, frameId, width, height, stridePixels, pixelFormat +`RGBA8888`, mimeType and stale. Stride describes the original framebuffer, not PNG +compression/padding. Logical and render frame counters are independent. + +The adapter MUST NOT invent a frame when none exists or substitute another +session's image. The same neutral capture feeds DEV and MCP. Real runtime +production/cross-language equality remain phase 4 gates; encoding test pixels in +contract tests does not satisfy that integration requirement. + +## 7. Conformance and Delivery Boundary + +Contract tests validate every tool's example, authority level, required project/ +task IDs, invalid types/unknown fields, exclusive operation lookup, input ranges, +pagination, result envelopes, PNG bytes and independent frame identities. +HTTP tests use a real loopback listener/client and exercise initialization, +authentication, Origin, endpoint/method/version handling, tool dispatch, malformed +or oversized input, closure, restart and old-token rejection. Provider doubles +exist only in tests. Composition starts/closes transport with Studio. + +Step 16's production registry is empty until functional handlers are composed; +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/docs/specs/studio/README.md b/docs/specs/studio/README.md index 1d8ad82b..f3ae8b27 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -57,6 +57,7 @@ The current Studio core corpus is: 5. [`8. Project-Local Studio State Specification.md`](8.%20Project-Local%20Studio%20State%20Specification.md) 6. [`9. Studio Core and Adapter Architecture Specification.md`](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md) 7. [`10. DEV and Automation Specification.md`](10.%20DEV%20and%20Automation%20Specification.md) +8. [`11. MCP Tools and Project Knowledge Contract.md`](11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) ## Reading Order @@ -68,7 +69,8 @@ Recommended order: 4. assets workspace behavior; 5. project-local Studio state behavior; 6. Studio Core, adapter, composition, and external integration boundaries; -7. DEV authority, document handoff, automation operations/captures and phased integration gates. +7. DEV authority, document handoff, automation operations/captures and phased integration gates; +8. MCP transport/tool schemas and project/language knowledge contracts. ## Current Wave Notes 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 36a39a5a..dbfe0ec8 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -290,6 +290,22 @@ public class StudioApplicationConfiguration { activityHistoryStore); } + @Bean + p.studio.app.mcp.McpToolCatalog mcpToolCatalog(ObjectMapper mapper) { + return new p.studio.app.mcp.McpToolCatalog(mapper); + } + + @Bean + p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper) { + // Providers are connected in PLN-0139 steps 17–20. Never advertise placeholders. + return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, java.util.Map.of()); + } + + @Bean(initMethod = "start", destroyMethod = "close") + p.studio.app.mcp.LocalMcpServer localMcpServer(ObjectMapper mapper, p.studio.app.mcp.McpToolRegistry tools) { + return new p.studio.app.mcp.LocalMcpServer(mapper, tools); + } + private static Path resolveDefaultProjectsRoot() { Path cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize(); while (cursor != null) { diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java b/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java new file mode 100644 index 00000000..3f781557 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java @@ -0,0 +1,48 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.HashSet; + +/** Validator for the deliberately small JSON Schema vocabulary in our packaged schemas. + * Not a general-purpose JSON Schema engine; never accepts client-supplied schemas. */ +final class ContractSchema { + private ContractSchema() { } + static void validate(JsonNode schema, JsonNode value) { + if (value == null) fail(); + if (schema.has("oneOf")) { + int matches = 0; + for (var branch : schema.get("oneOf")) if (matches(branch, value)) matches++; + if (matches != 1) fail(); + } + if (schema.has("not") && matches(schema.get("not"), value)) fail(); + if (schema.has("const") && !schema.get("const").equals(value)) fail(); + if (schema.has("type")) { + boolean valid = switch (schema.get("type").asText()) { + case "object" -> value.isObject(); + case "array" -> value.isArray(); + case "string" -> value.isTextual(); + case "integer" -> value.isIntegralNumber() && value.canConvertToLong(); + case "boolean" -> value.isBoolean(); + default -> throw new IllegalStateException("Unsupported packaged schema type"); + }; + if (!valid) fail(); + } + if (schema.has("minLength") && value.textValue().codePointCount(0, value.textValue().length()) < schema.get("minLength").intValue()) fail(); + if (schema.has("minimum") && value.longValue() < schema.get("minimum").longValue()) fail(); + if (schema.has("maximum") && value.longValue() > schema.get("maximum").longValue()) fail(); + if (schema.has("required")) for (var key : schema.get("required")) if (!value.has(key.asText())) fail(); + if (schema.has("properties")) { + var allowed = new HashSet(); + schema.get("properties").fields().forEachRemaining(field -> { + allowed.add(field.getKey()); + if (value.has(field.getKey())) validate(field.getValue(), value.get(field.getKey())); + }); + if (!schema.path("additionalProperties").asBoolean(true)) value.fieldNames().forEachRemaining(key -> { if (!allowed.contains(key)) fail(); }); + } + if (schema.has("items")) for (var item : value) validate(schema.get("items"), item); + } + private static boolean matches(JsonNode schema, JsonNode value) { + try { validate(schema, value); return true; } catch (IllegalArgumentException failure) { return false; } + } + private static void fail() { throw new IllegalArgumentException("Arguments do not match the tool contract"); } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java b/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java new file mode 100644 index 00000000..b1b96e78 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java @@ -0,0 +1,203 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.*; +import com.sun.net.httpserver.*; +import java.io.IOException; +import java.net.*; +import java.nio.ByteBuffer; +import java.nio.charset.*; +import java.security.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; + +/** Local MCP transport only. A connection session never represents a project grant or task. */ +public final class LocalMcpServer implements AutoCloseable { + public static final String PROTOCOL_VERSION = "2025-06-18"; + private static final int MAX_BODY_BYTES = 1024 * 1024; + private static final int MAX_CONNECTION_SESSIONS = 128; + private final ObjectMapper mapper; + private final McpToolRegistry tools; + private final Map sessions = new ConcurrentHashMap<>(); + private final SecureRandom random = new SecureRandom(); + private HttpServer server; + private ExecutorService executor; + private ScheduledExecutorService deadlines; + private volatile Connection connection; + + public LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools) { + this.mapper = mapper.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + this.tools = Objects.requireNonNull(tools); + } + + public synchronized void start() throws IOException { + if (server != null) return; + // No configurable bind address: remote and wildcard exposure cannot be enabled accidentally. + var next = HttpServer.create(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 32); + var workers = new ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(32), + Thread.ofPlatform().daemon().name("studio-mcp-", 1).factory(), new ThreadPoolExecutor.AbortPolicy()); + var timers = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-deadlines").factory()); + try { + connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"), secret()); + deadlines = timers; + next.createContext("/mcp", this::handle); + next.setExecutor(workers); + next.start(); + executor = workers; server = next; + } catch (RuntimeException failure) { + next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null; + throw failure; + } + } + public Connection connection() { + var current = connection; + if (current == null) throw new IllegalStateException("MCP is not running"); + return current; + } + public synchronized boolean isRunning() { return server != null; } + @Override public synchronized void close() { + if (server == null) return; + connection = null; server.stop(0); server = null; + sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow(); + } + + /** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */ + public static final class Connection { + private final URI endpoint; + private final String token; + private Connection(URI endpoint, String token) { this.endpoint = endpoint; this.token = token; } + public URI endpoint() { return endpoint; } + public String authorizationHeader() { return "Bearer " + token; } + @Override public String toString() { return "LocalMcpConnection[endpoint=" + endpoint + ", credentials=REDACTED]"; } + } + + private void handle(HttpExchange exchange) throws IOException { + // Bounds stalled body reads and transport responses, not guest simulated time or task lifetime. + var timeout = deadlines.schedule(exchange::close, 15, TimeUnit.SECONDS); + try (exchange) { + exchange.getResponseHeaders().set("Cache-Control", "no-store"); + exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff"); + var current = connection; + if (current == null) { empty(exchange, 503); return; } + if (!"/mcp".equals(exchange.getRequestURI().getRawPath()) || exchange.getRequestURI().getRawQuery() != null) { empty(exchange, 404); return; } + var headers = exchange.getRequestHeaders(); + String origin = single(headers, "Origin"); + String authority = current.endpoint().getRawAuthority(); + if (!exchange.getRemoteAddress().getAddress().isLoopbackAddress() + || !authority.equals(single(headers, "Host")) + || origin != null && !("http://" + authority).equals(origin)) { empty(exchange, 403); return; } + String authorization = single(headers, "Authorization"); + if (authorization == null || !MessageDigest.isEqual(current.authorizationHeader().getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) { + empty(exchange, 401); return; + } + String version = single(headers, "MCP-Protocol-Version"); + if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; } + String sessionId = single(headers, "Mcp-Session-Id"); + AtomicBoolean initialized = sessionId == null ? null : sessions.get(sessionId); + if (sessionId != null && initialized == null) { empty(exchange, 404); return; } + String method = exchange.getRequestMethod(); + if (method.equals("GET")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; } + if (method.equals("DELETE")) { + if (sessionId == null) { empty(exchange, 400); return; } + sessions.remove(sessionId); empty(exchange, 200); return; // No project/task release. + } + if (!method.equals("POST")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; } + if (!accepts(headers, "application/json") || !accepts(headers, "text/event-stream")) { empty(exchange, 406); return; } + String contentType = single(headers, "Content-Type"); + if (contentType == null || !contentType.split(";", 2)[0].trim().equalsIgnoreCase("application/json")) { empty(exchange, 415); return; } + byte[] body = exchange.getRequestBody().readNBytes(MAX_BODY_BYTES + 1); + if (body.length > MAX_BODY_BYTES) { empty(exchange, 413); return; } + JsonNode message; + try { + String json = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body)).toString(); + message = mapper.readTree(json); + } catch (IOException invalid) { send(exchange, 400, error(NullNode.instance, -32700, "Invalid JSON")); return; } + if (message == null || !message.isObject() || !message.path("jsonrpc").isTextual() || !message.path("jsonrpc").asText().equals("2.0") + || message.has("id") && !(message.get("id").isTextual() || message.get("id").isNumber())) { + send(exchange, 400, error(NullNode.instance, -32600, "Invalid request")); return; + } + JsonNode id = message.path("id"); + String rpc = message.path("method").asText(); + if (!message.path("method").isTextual() || rpc.isBlank() || message.has("result") || message.has("error")) { + // This server issues no requests, but acknowledge well-formed client responses. + if (initialized != null && message.has("id") && !message.has("method") && message.has("result") != message.has("error")) empty(exchange, 202); + else send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32600, "Invalid request")); + return; + } + JsonNode params = message.has("params") ? message.get("params") : mapper.createObjectNode(); + if (!params.isObject()) { send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid parameters")); return; } + if (rpc.equals("initialize")) { + if (id.isMissingNode() || initialized != null || !params.path("protocolVersion").isTextual() + || !params.path("capabilities").isObject() || !params.path("clientInfo").isObject() + || !params.path("clientInfo").path("name").isTextual() || !params.path("clientInfo").path("version").isTextual()) { + send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return; + } + synchronized (sessions) { + if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; } + sessionId = secret(); sessions.put(sessionId, new AtomicBoolean()); + } + exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId); + var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION); + result.putObject("capabilities").putObject("tools").put("listChanged", false); + result.putObject("serverInfo").put("name", "prometeu-studio-mcp").put("version", "1.0"); + result.put("instructions", "Read project context and indexed references. Human grant in DEV precedes acquisition. Edit saved project files with your native tools, never SDK/external libraries. Validate with LSP/build and explicitly release. Studio revocation does not stop your external file writes. Reconnect with new configuration after Studio restart."); + send(exchange, 200, response(id, result)); return; + } + if (initialized == null) { empty(exchange, 400); return; } + if (id.isMissingNode()) { + if (rpc.equals("notifications/initialized")) initialized.set(true); + // Notifications do not implicitly cancel an already returned operationId or release authority. + empty(exchange, 202); return; + } + if (!initialized.get() && !rpc.equals("ping")) { send(exchange, 200, error(id, -32600, "Initialization required")); return; } + try { + JsonNode result = switch (rpc) { + case "ping" -> mapper.createObjectNode(); + case "tools/list" -> { + if (params.has("cursor")) throw new IllegalArgumentException("No further tool page"); + yield mapper.createObjectNode().set("tools", tools.descriptors()); + } + case "tools/call" -> { + if (!params.path("name").isTextual()) throw new IllegalArgumentException("Missing tool name"); + yield tools.call(params.get("name").asText(), params.get("arguments")).wire(); + } + default -> null; + }; + send(exchange, 200, result == null ? error(id, -32601, "Method not found") : response(id, result)); + } catch (IllegalArgumentException invalid) { send(exchange, 200, error(id, -32602, "Invalid tool or parameters")); } + catch (RuntimeException failure) { send(exchange, 200, error(id, -32603, "Internal error")); } + } finally { timeout.cancel(false); } + } + private String secret() { byte[] bytes = new byte[32]; random.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } + private static String single(Headers headers, String name) { + var values = headers.get(name); + return values == null ? null : values.size() == 1 ? values.getFirst() : ""; + } + private static boolean accepts(Headers headers, String type) { + return headers.getOrDefault("Accept", List.of()).stream().flatMap(s -> Arrays.stream(s.split(","))) + .anyMatch(range -> { + var parts = range.trim().split(";"); + if (!parts[0].trim().equalsIgnoreCase(type)) return false; + for (int index = 1; index < parts.length; index++) { + var parameter = parts[index].trim(); + if (parameter.startsWith("q=")) { + try { double q = Double.parseDouble(parameter.substring(2)); if (!(q > 0 && q <= 1)) return false; } + catch (NumberFormatException invalid) { return false; } + } + } + return true; + }); + } + private ObjectNode response(JsonNode id, JsonNode result) { var value = mapper.createObjectNode().put("jsonrpc", "2.0"); value.set("id", id); value.set("result", result); return value; } + private ObjectNode error(JsonNode id, int code, String message) { var value = mapper.createObjectNode().put("jsonrpc", "2.0"); value.set("id", id); value.putObject("error").put("code", code).put("message", message); return value; } + private void send(HttpExchange exchange, int status, JsonNode value) throws IOException { + byte[] bytes = mapper.writeValueAsBytes(value); + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.sendResponseHeaders(status, bytes.length); exchange.getResponseBody().write(bytes); + } + private static void empty(HttpExchange exchange, int status) throws IOException { exchange.sendResponseHeaders(status, -1); } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java new file mode 100644 index 00000000..559a9665 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java @@ -0,0 +1,39 @@ +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 java.io.IOException; +import java.util.*; + +/** Packaged v1 contract, not a claim that every provider has been composed. */ +public final class McpToolCatalog { + private final Map definitions; + public McpToolCatalog(ObjectMapper mapper) { + try (var input = getClass().getResourceAsStream("/mcp/studio-tools-v1.json")) { + var root = mapper.readTree(Objects.requireNonNull(input, "Missing MCP contract")); + var loaded = new LinkedHashMap(); + for (var tool : root.required("tools")) { + if (loaded.put(tool.required("name").asText(), tool) != null) throw new IllegalStateException("Duplicate MCP tool"); + ContractSchema.validate(tool.required("inputSchema"), tool.required("exampleArguments")); + } + definitions = Collections.unmodifiableMap(loaded); + } catch (IOException failure) { throw new IllegalStateException("Cannot read packaged MCP contract", failure); } + } + public Set names() { return definitions.keySet(); } + public JsonNode definition(String name) { + var definition = definitions.get(name); + if (definition == null) throw new IllegalArgumentException("Unknown tool"); + return definition.deepCopy(); + } + public ObjectNode descriptor(String name) { + var result = (ObjectNode) definition(name); + result.remove(List.of("authority", "exampleArguments", "exampleValue")); + return result; + } + public void validateArguments(String name, JsonNode arguments) { + ContractSchema.validate(definition(name).required("inputSchema"), arguments); + var root = arguments.required("projectRoot").asText(); + if (!java.nio.file.Path.of(root).isAbsolute()) throw new IllegalArgumentException("projectRoot must be absolute"); + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java new file mode 100644 index 00000000..48ce2b35 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java @@ -0,0 +1,40 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import p.studio.api.automation.AutomationFailure; +import p.studio.api.automation.ControlDeniedException; +import java.util.Map; +import java.util.function.Function; + +/** Immutable adapter dispatch. Services, not this transport, own authority and operations. */ +public final class McpToolRegistry { + private final McpToolCatalog catalog; + private final ObjectMapper mapper; + private final Map> handlers; + public McpToolRegistry(McpToolCatalog catalog, ObjectMapper mapper, Map> handlers) { + this.catalog = catalog; this.mapper = mapper; this.handlers = Map.copyOf(handlers); + handlers.keySet().forEach(catalog::definition); + } + public ArrayNode descriptors() { + var descriptors = mapper.createArrayNode(); + catalog.names().stream().filter(handlers::containsKey).forEach(name -> descriptors.add(catalog.descriptor(name))); + return descriptors; + } + public McpToolResult call(String name, JsonNode arguments) { + var handler = handlers.get(name); + if (handler == null) throw new IllegalArgumentException("Unknown or unavailable tool"); + catalog.validateArguments(name, arguments); + try { return handler.apply(arguments); } + catch (ControlDeniedException denied) { + var code = switch (denied.status()) { + case INVALID_TASK -> AutomationFailure.Code.INVALID_TASK; + case NOT_GRANTED -> AutomationFailure.Code.NOT_GRANTED; + case CLOSED -> AutomationFailure.Code.CLOSED; + default -> AutomationFailure.Code.BUSY; + }; + return McpToolResult.failure(mapper, new AutomationFailure(code, "Project authority rejected the call")); + } + } +} 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 new file mode 100644 index 00000000..611e7374 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolResult.java @@ -0,0 +1,41 @@ +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.AutomationFailure; +import p.studio.api.automation.CanonicalCapture; +import java.util.Base64; +import java.util.Objects; + +/** Wire projection only. Images are the same bytes held by the neutral DEV snapshot. */ +public final class McpToolResult { + private final ObjectNode wire; + private McpToolResult(ObjectNode wire) { this.wire = wire; } + public ObjectNode wire() { return wire.deepCopy(); } + public static McpToolResult success(ObjectMapper mapper, ObjectNode value) { + return envelope(mapper, mapper.createObjectNode().put("status", "ok").set("value", value.deepCopy()), false); + } + public static McpToolResult failure(ObjectMapper mapper, AutomationFailure failure) { + var data = mapper.createObjectNode().put("status", "error"); + data.set("error", mapper.valueToTree(failure)); + return envelope(mapper, data, true); + } + public static McpToolResult capture(ObjectMapper mapper, CanonicalCapture capture, boolean stale) { + Objects.requireNonNull(capture); + var metadata = mapper.createObjectNode().put("sessionId", capture.sessionId()).put("buildId", capture.buildId()) + .put("logicalFrameIndex", capture.logicalFrameIndex()).put("frameId", capture.frameId()) + .put("width", capture.width()).put("height", capture.height()).put("stridePixels", capture.stridePixels()) + .put("pixelFormat", "RGBA8888").put("mimeType", "image/png").put("stale", stale); + var result = success(mapper, metadata); + result.wire.withArray("content").addObject().put("type", "image").put("mimeType", "image/png") + .put("data", Base64.getEncoder().encodeToString(capture.png())); + return result; + } + private static McpToolResult envelope(ObjectMapper mapper, JsonNode data, boolean error) { + var wire = mapper.createObjectNode().put("isError", error); + wire.set("structuredContent", data); + wire.putArray("content").addObject().put("type", "text").put("text", data.toString()); + return new McpToolResult(wire); + } +} diff --git a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json new file mode 100644 index 00000000..70e8ef26 --- /dev/null +++ b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json @@ -0,0 +1,1784 @@ +{ + "contractVersion": "1.0", + "tools": [ + { + "name": "studio_project_context", + "authority": "authenticated", + "description": "Read the open project's manifest-driven language, capability, reference and edit-scope context.", + "inputSchema": { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1, + "description": "Absolute root of an open project. Never inferred from UI focus." + } + }, + "required": [ + "projectRoot" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game" + }, + "exampleValue": { + "projectRoot": "/projects/game", + "projectName": "game", + "languages": [], + "libraries": [], + "editableRoots": [ + "/projects/game" + ], + "readOnlyRoots": [], + "references": [], + "limitations": [ + "Example context; installed provider supplies real support." + ] + } + }, + { + "name": "studio_reference_read", + "authority": "authenticated", + "description": "Read only an indexed local language/SDK reference, paginated in Unicode code points.", + "inputSchema": { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1, + "description": "Absolute root of an open project. Never inferred from UI focus." + }, + "referenceId": { + "type": "string", + "minLength": 1 + }, + "offset": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 16000, + "default": 4000 + } + }, + "required": [ + "projectRoot", + "referenceId" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "referenceId": "pbs.quickstart", + "offset": 0, + "limit": 4000 + }, + "exampleValue": { + "referenceId": "pbs.quickstart", + "offset": 0, + "total": 7, + "nextOffset": null, + "text": "Example" + } + }, + { + "name": "studio_control_acquire", + "authority": "granted", + "description": "Acquire the task after explicit human grant in DEV. Authentication alone is insufficient.", + "inputSchema": { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1, + "description": "Absolute root of an open project. Never inferred from UI focus." + } + }, + "required": [ + "projectRoot" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game" + }, + "exampleValue": { + "taskId": "task-example", + "state": "AGENT_WORKING" + } + }, + { + "name": "studio_control_release", + "authority": "task", + "description": "Invalidate this task, stop managed work and refresh documents before manual return.", + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example" + }, + "exampleValue": { + "state": "MANUAL" + } + }, + { + "name": "studio_language_query", + "authority": "task", + "description": "Query supported project LSP capabilities after synchronizing saved files. Returns refactoring proposals, never applies edits.", + "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." + }, + "operation": { + "type": "string", + "minLength": 1 + }, + "parameters": { + "type": "object", + "properties": { + "uri": { + "type": "string", + "minLength": 1 + }, + "position": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "minimum": 0 + }, + "character": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "line", + "character" + ], + "additionalProperties": false + }, + "range": { + "type": "object", + "properties": { + "start": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "minimum": 0 + }, + "character": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "line", + "character" + ], + "additionalProperties": false + }, + "end": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "minimum": 0 + }, + "character": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "line", + "character" + ], + "additionalProperties": false + } + }, + "required": [ + "start", + "end" + ], + "additionalProperties": false + }, + "positions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "minimum": 0 + }, + "character": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "line", + "character" + ], + "additionalProperties": false + } + }, + "query": { + "type": "string" + }, + "newName": { + "type": "string", + "minLength": 1 + }, + "includeDeclaration": { + "type": "boolean" + }, + "itemId": { + "type": "string", + "minLength": 1 + } + }, + "required": [], + "additionalProperties": false + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "parameters" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "operation": "definition", + "parameters": { + "uri": "file:///projects/game/src/main.pbs", + "position": { + "line": 0, + "character": 0 + } + } + }, + "exampleValue": { + "operation": "definition", + "locations": [], + "limitations": [] + } + }, + { + "name": "studio_build_start", + "authority": "task", + "description": "Start saved-source compile and pack; return operationId promptly. Reuse clientRequestId only for identical parameters.", + "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." + }, + "clientRequestId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "clientRequestId" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "clientRequestId": "build-example" + }, + "exampleValue": { + "operationId": "operation-build", + "clientRequestId": "build-example", + "state": "PENDING" + } + }, + { + "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.", + "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." + }, + "buildId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "buildId" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "buildId": "build-example" + }, + "exampleValue": { + "sessionId": "runtime-example", + "buildId": "build-example" + } + }, + { + "name": "studio_headless_reset", + "authority": "task", + "description": "reset the task-owned headless session; preserve runtime semantics and task authority.", + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example" + }, + "exampleValue": { + "sessionId": "runtime-example" + } + }, + { + "name": "studio_headless_clear_input", + "authority": "task", + "description": "clear_input the task-owned headless session; preserve runtime semantics and task authority.", + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example" + }, + "exampleValue": { + "sessionId": "runtime-example" + } + }, + { + "name": "studio_headless_capture", + "authority": "task", + "description": "capture the task-owned headless session; preserve runtime semantics and task authority.", + "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" + } + }, + "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", + "buildId": "build-example", + "logicalFrameIndex": 9, + "frameId": 4, + "width": 1, + "height": 1, + "stridePixels": 1, + "pixelFormat": "RGBA8888", + "mimeType": "image/png", + "stale": false + } + }, + { + "name": "studio_headless_state", + "authority": "task", + "description": "state the task-owned headless session; preserve runtime semantics and task authority.", + "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" + } + }, + "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_fault", + "authority": "task", + "description": "fault the task-owned headless session; preserve runtime semantics and task authority.", + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example" + }, + "exampleValue": { + "fault": null + } + }, + { + "name": "studio_headless_shutdown", + "authority": "task", + "description": "shutdown the task-owned headless session; preserve runtime semantics and task authority.", + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example" + }, + "exampleValue": { + "sessionId": "runtime-example" + } + }, + { + "name": "studio_headless_set_input", + "authority": "task", + "description": "Replace normalized input. Omitted controls become false/zero, not a partial patch.", + "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." + }, + "input": { + "type": "object", + "properties": { + "up": { + "type": "boolean", + "default": false + }, + "down": { + "type": "boolean", + "default": false + }, + "left": { + "type": "boolean", + "default": false + }, + "right": { + "type": "boolean", + "default": false + }, + "a": { + "type": "boolean", + "default": false + }, + "b": { + "type": "boolean", + "default": false + }, + "x": { + "type": "boolean", + "default": false + }, + "y": { + "type": "boolean", + "default": false + }, + "l": { + "type": "boolean", + "default": false + }, + "r": { + "type": "boolean", + "default": false + }, + "start": { + "type": "boolean", + "default": false + }, + "select": { + "type": "boolean", + "default": false + }, + "touch": { + "type": "boolean", + "default": false + }, + "touchX": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647, + "default": 0 + }, + "touchY": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647, + "default": 0 + } + }, + "required": [], + "additionalProperties": false + } + }, + "required": [ + "projectRoot", + "taskId", + "input" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "input": { + "a": true, + "touchX": 0, + "touchY": 0 + } + }, + "exampleValue": { + "sessionId": "runtime-example" + } + }, + { + "name": "studio_headless_advance", + "authority": "task", + "description": "Start bounded frame advancement and return operationId promptly; results include the canonical PNG. Do not blindly retry lost responses.", + "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." + }, + "clientRequestId": { + "type": "string", + "minLength": 1 + }, + "frames": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "projectRoot", + "taskId", + "clientRequestId", + "frames" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "clientRequestId": "advance-example", + "frames": 60 + }, + "exampleValue": { + "operationId": "operation-advance", + "clientRequestId": "advance-example", + "state": "PENDING" + } + }, + { + "name": "studio_operation_get", + "authority": "task", + "description": "Read a task-local operation by exactly one of operationId or clientRequestId, including known progress, typed result and image.", + "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." + }, + "operationId": { + "type": "string", + "minLength": 1 + }, + "clientRequestId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId" + ], + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "operationId" + ], + "not": { + "required": [ + "clientRequestId" + ] + } + }, + { + "required": [ + "clientRequestId" + ], + "not": { + "required": [ + "operationId" + ] + } + } + ] + }, + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "operationId": "operation-advance" + }, + "exampleValue": { + "operationId": "operation-advance", + "clientRequestId": "advance-example", + "state": "RUNNING", + "progress": { + "requestedFrames": 60, + "completedFrames": 12 + }, + "result": null + } + }, + { + "name": "studio_operation_cancel", + "authority": "task", + "description": "Request cancellation of an owned operation. Acknowledgement is not worker termination or task release.", + "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." + }, + "operationId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operationId" + ], + "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" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "operationId": "operation-advance" + }, + "exampleValue": { + "operationId": "operation-advance", + "cancellationRequested": true + } + } + ] +} 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 897df9b9..d9063b9e 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -21,13 +21,17 @@ class StudioApplicationConfigurationTest { .headless(true) .run(); final ExecutorService executor = context.getBean(ExecutorService.class); + final var mcp = context.getBean(p.studio.app.mcp.LocalMcpServer.class); try (context) { assertNotNull(context.getBean(StudioUiFactory.class)); assertNotNull(context.getBean(PackerWorkspaceService.class)); assertNotNull(context.getBean(OperationExecutor.class)); assertFalse(context.getClass().getName().contains("WebServer")); assertFalse(executor.isShutdown()); + assertTrue(mcp.isRunning()); + assertTrue(context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors().isEmpty()); } assertTrue(executor.isShutdown()); + assertFalse(mcp.isRunning()); } } diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java new file mode 100644 index 00000000..b2c14105 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java @@ -0,0 +1,133 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import java.net.URI; +import java.net.http.*; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import p.studio.api.automation.*; +import static org.junit.jupiter.api.Assertions.*; + +class LocalMcpServerTest { + final ObjectMapper mapper = new ObjectMapper(); + final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build(); + LocalMcpServer server; + String session; + AtomicInteger calls; + + @BeforeEach void start() throws Exception { + calls = new AtomicInteger(); + server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of( + "studio_project_context", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("projectRoot", args.get("projectRoot").asText())); }, + "studio_control_acquire", args -> McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.NOT_GRANTED, "Human grant required"))))); + server.start(); + } + @AfterEach void close() { server.close(); client.close(); } + HttpResponse request(String method, URI uri, String body, String token, String origin, String protocol, String sessionId) throws Exception { + var request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(5)) + .header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json"); + if (token != null) request.header("Authorization", token); + if (origin != null) request.header("Origin", origin); + if (protocol != null) request.header("MCP-Protocol-Version", protocol); + if (sessionId != null) request.header("Mcp-Session-Id", sessionId); + return client.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString()); + } + HttpResponse post(String body) throws Exception { + return request("POST", server.connection().endpoint(), body, server.connection().authorizationHeader(), null, LocalMcpServer.PROTOCOL_VERSION, session); + } + static String init() { return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1\"},\"capabilities\":{}}}"; } + void initialize() throws Exception { + var response = post(init()); assertEquals(200, response.statusCode()); + session = response.headers().firstValue("Mcp-Session-Id").orElseThrow(); + assertEquals(LocalMcpServer.PROTOCOL_VERSION, mapper.readTree(response.body()).path("result").path("protocolVersion").asText()); + assertEquals(202, post("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}").statusCode()); + } + @Test void lifecycleNegotiatesListsAndCallsOnlyActualHandlers() throws Exception { + initialize(); + var listed = mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}").body()); + assertEquals(2, listed.path("result").path("tools").size()); + var response = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}"); + assertEquals(200, response.statusCode()); assertEquals(1, calls.get()); + assertEquals("ok", mapper.readTree(response.body()).path("result").path("structuredContent").path("status").asText()); + assertEquals(200, request("DELETE", server.connection().endpoint(), null, server.connection().authorizationHeader(), null, null, session).statusCode()); + assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode()); + } + @Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception { + var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader(); + assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0); + assertEquals(401, request("POST", endpoint, init(), null, null, null, null).statusCode()); + assertEquals(401, request("POST", endpoint, init(), "Bearer wrong", null, null, null).statusCode()); + for (var origin : List.of("null", "https://evil.example", "http://127.0.0.1:1", "http://localhost:" + endpoint.getPort())) + assertEquals(403, request("POST", endpoint, init(), token, origin, null, null).statusCode()); + assertEquals(200, request("POST", endpoint, init(), token, "http://" + endpoint.getRawAuthority(), null, null).statusCode()); + assertEquals(0, calls.get()); + assertFalse(server.connection().toString().contains(token.substring(7))); + } + @Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception { + initialize(); var old = server.connection(); server.close(); + assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection); + server.start(); assertFalse(old.authorizationHeader().equals(server.connection().authorizationHeader())); + assertEquals(401, request("POST", server.connection().endpoint(), init(), old.authorizationHeader(), null, null, null).statusCode()); + assertEquals(404, post(init()).statusCode()); + session = null; initialize(); + } + @Test void malformedBodiesVersionsAndToolsCannotReachProviders() throws Exception { + initialize(); + assertEquals(400, post("{not json}").statusCode()); + assertEquals(400, post("[]").statusCode()); + assertEquals(400, post("{\"jsonrpc\":2.0,\"id\":1,\"method\":\"ping\"}").statusCode()); + assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"method\":123}").statusCode()); + assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"id\":2,\"method\":\"ping\"}").statusCode()); + assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"} {}").statusCode()); + assertEquals(400, request("POST", server.connection().endpoint(), init(), server.connection().authorizationHeader(), null, "unknown", session).statusCode()); + var bad = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"relative\"}}}"); + assertEquals(-32602, mapper.readTree(bad.body()).path("error").path("code").intValue()); assertEquals(0, calls.get()); + assertEquals(413, post(" ".repeat(1024 * 1024 + 1)).statusCode()); + } + @Test void exactEndpointNoSseAndInitializationAreEnforced() throws Exception { + var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader(); + assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").statusCode()); + var initialized = post(init()); session = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow(); + assertEquals(-32600, mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").body()).path("error").path("code").asInt()); + assertEquals(405, request("GET", endpoint, null, token, null, null, session).statusCode()); + assertEquals(404, request("POST", URI.create(endpoint + "/nested"), init(), token, null, null, null).statusCode()); + assertEquals(404, request("POST", URI.create(endpoint + "?token=forbidden"), init(), token, null, null, null).statusCode()); + assertEquals(0, calls.get()); + } + @Test void authenticatedConnectionDoesNotGrantControl() throws Exception { + initialize(); + var denied = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_control_acquire\",\"arguments\":{\"projectRoot\":\"/project\"}}}"); + var result = mapper.readTree(denied.body()).path("result"); + assertTrue(result.path("isError").asBoolean()); assertEquals("NOT_GRANTED", result.path("structuredContent").path("error").path("code").asText()); + } + + @Test void hostileHostAndDuplicateOriginAreRejectedEvenWithValidCredentials() throws Exception { + var connection = server.connection(); + try (var socket = new java.net.Socket("127.0.0.1", connection.endpoint().getPort())) { + socket.setSoTimeout(3000); + String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + connection.authorizationHeader() + + "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + socket.getOutputStream().write(request.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + var status = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())).readLine(); + assertTrue(status.contains("403")); + } + var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader()) + .header("Origin", "http://" + connection.endpoint().getRawAuthority()).header("Origin", "https://evil.example") + .POST(HttpRequest.BodyPublishers.ofString(init())).build(); + assertEquals(403, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()); + } + + @Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception { + var connection = server.connection(); + var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader()) + .header("Accept", "application/json;q=1, text/event-stream;q=0.5").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(init())).build(); + assertEquals(200, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()); + var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader()) + .header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofByteArray(new byte[]{(byte) 0xc3, (byte) 0x28})).build(); + assertEquals(400, client.send(invalid, HttpResponse.BodyHandlers.discarding()).statusCode()); + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java new file mode 100644 index 00000000..02746a40 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java @@ -0,0 +1,81 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; +import p.studio.api.automation.*; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; + +class McpContractTest { + final ObjectMapper mapper = new ObjectMapper(); + final McpToolCatalog catalog = new McpToolCatalog(mapper); + + @Test void everyToolHasValidExampleAuthorityAndResultEnvelope() { + assertEquals(17, catalog.names().size()); + for (var name : catalog.names()) { + var definition = catalog.definition(name); + catalog.validateArguments(name, definition.get("exampleArguments")); + var result = McpToolResult.success(mapper, (ObjectNode) definition.get("exampleValue")); + ContractSchema.validate(definition.get("outputSchema"), result.wire().get("structuredContent")); + var failure = McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.INVALID_TASK, "Revoked")); + ContractSchema.validate(definition.get("outputSchema"), failure.wire().get("structuredContent")); + assertTrue(Set.of("authenticated", "granted", "task").contains(definition.get("authority").asText())); + assertEquals(definition.get("authority").asText().equals("task"), definition.get("inputSchema").get("properties").has("taskId")); + assertFalse(catalog.descriptor(name).has("exampleArguments")); + } + } + @Test void missingRootTaskUnexpectedFieldsAndWrongTypesAreRejected() { + for (var name : catalog.names()) { + ObjectNode sample = catalog.definition(name).get("exampleArguments").deepCopy(); + sample.remove("projectRoot"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample)); + sample.put("projectRoot", "relative/root"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample)); + sample.put("projectRoot", "/project").put("shell", "forbidden"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample)); + sample.remove("shell"); sample.put("projectRoot", 12); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample)); + if (sample.has("taskId")) { + sample.put("projectRoot", "/project").remove("taskId"); + assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample)); + } + } + } + @Test void lookupIsExclusiveAndFrameInputAndPaginationAreBounded() { + ObjectNode lookup = catalog.definition("studio_operation_get").get("exampleArguments").deepCopy(); + lookup.put("clientRequestId", "request"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_operation_get", lookup)); + lookup.remove(List.of("clientRequestId", "operationId")); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_operation_get", lookup)); + lookup.put("clientRequestId", "request"); catalog.validateArguments("studio_operation_get", lookup); + ObjectNode advance = catalog.definition("studio_headless_advance").get("exampleArguments").deepCopy(); + advance.put("frames", -1); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_headless_advance", advance)); + advance.put("frames", 1.5); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_headless_advance", advance)); + ObjectNode reference = catalog.definition("studio_reference_read").get("exampleArguments").deepCopy(); + reference.put("limit", 0); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_reference_read", reference)); + ObjectNode input = catalog.definition("studio_headless_set_input").get("exampleArguments").deepCopy(); + ((ObjectNode) input.get("input")).put("touchX", Long.MAX_VALUE); + assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_headless_set_input", input)); + } + @Test void imageBytesAndMetadataArePreservedWithoutFileTransport() throws Exception { + byte[] png = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9l0AAAAASUVORK5CYII="); + var capture = new CanonicalCapture("session", "build", 123, 7, 1, 1, 1, png); + var wire = McpToolResult.capture(mapper, capture, true).wire(); + assertArrayEquals(png, Base64.getDecoder().decode(wire.get("content").get(1).get("data").asText())); + assertEquals("image/png", wire.get("content").get(1).get("mimeType").asText()); + assertEquals(wire.get("structuredContent").toString(), wire.get("content").get(0).get("text").asText()); + var value = wire.get("structuredContent").get("value"); + assertEquals(123, value.get("logicalFrameIndex").asLong()); assertEquals(7, value.get("frameId").asLong()); + assertTrue(value.get("stale").asBoolean()); assertEquals("RGBA8888", value.get("pixelFormat").asText()); + } + @Test void unavailableHandlersAreNotAdvertisedOrInvoked() { + var registry = new McpToolRegistry(catalog, mapper, Map.of()); + assertTrue(registry.descriptors().isEmpty()); + assertThrows(IllegalArgumentException.class, () -> registry.call("studio_project_context", catalog.definition("studio_project_context").get("exampleArguments"))); + } + @Test void neutralLookupProgressAndReferencesDoNotInventUnknownValues() { + assertThrows(IllegalArgumentException.class, () -> new OperationLookup(null, null)); + assertThrows(IllegalArgumentException.class, () -> new OperationLookup("id", "request")); + assertThrows(IllegalArgumentException.class, () -> new TrackedOperation.Progress(4L, 5L)); + assertNull(new TrackedOperation.Progress(null, null).completedFrames()); + assertFalse(ProjectKnowledge.Version.unknown().known()); + assertNull(ProjectKnowledge.Version.unknown().value()); + assertEquals(1, new ProjectKnowledge.ReferencePage("unicode", 0, 2, 1, "🎮").nextOffset()); + assertThrows(IllegalArgumentException.class, () -> new ProjectKnowledge.ReferencePage("invalid", 0, 1, 1, "ab")); + } +} diff --git a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java index 11c8ea44..fbbaa1b1 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java @@ -9,6 +9,13 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; @AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class) class StudioBoundaryArchTest { + @ArchTest + static final ArchRule automationTransportStaysInTheApp = noClasses() + .that().resideInAnyPackage("p.studio.api..", "p.studio.core..", "p.studio.ui..") + .should().dependOnClassesThat().resideInAnyPackage( + "p.studio.app.mcp..", "com.sun.net.httpserver..", "io.modelcontextprotocol..") + .because("DEC-0060 confines MCP and HTTP transport to application adapters"); + @ArchTest static final ArchRule staticContainerCannotReturn = noClasses() .that().resideInAnyPackage("p.studio..") diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java new file mode 100644 index 00000000..68388ab5 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java @@ -0,0 +1,15 @@ +package p.studio.api.automation; + +import java.util.Objects; + +/** Stable domain failure codes, independent of HTTP status and JSON-RPC errors. */ +public record AutomationFailure(Code code, String message) { + public enum Code { + PROJECT_NOT_OPEN, NOT_GRANTED, INVALID_TASK, BUSY, CLOSED, CLEANUP_FAILED, + UNSUPPORTED_LANGUAGE, UNSUPPORTED_CAPABILITY, REFERENCE_NOT_FOUND, DOCUMENTATION_UNAVAILABLE, + OUTSIDE_PROJECT_SCOPE, READ_ONLY_SCOPE, OPERATION_NOT_FOUND, CLIENT_REQUEST_CONFLICT, + RUNTIME_UNAVAILABLE, RUNTIME_INCOMPATIBLE, SESSION_NOT_FOUND, BUILD_NOT_FOUND, + NO_FRAME_AVAILABLE, LIMIT_EXCEEDED, NOT_CANCELABLE, INFRASTRUCTURE_FAILURE + } + public AutomationFailure { Objects.requireNonNull(code); Objects.requireNonNull(message); } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/OperationLookup.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/OperationLookup.java new file mode 100644 index 00000000..f7ddcf82 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/OperationLookup.java @@ -0,0 +1,11 @@ +package p.studio.api.automation; + +/** Exactly one lookup key, always scoped to a separately validated project/task identity. */ +public record OperationLookup(String operationId, String clientRequestId) { + public OperationLookup { + if ((operationId == null) == (clientRequestId == null) + || (operationId != null && operationId.isBlank()) + || (clientRequestId != null && clientRequestId.isBlank())) + throw new IllegalArgumentException("Supply exactly one nonblank operationId or clientRequestId"); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectKnowledge.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectKnowledge.java new file mode 100644 index 00000000..f998ee84 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectKnowledge.java @@ -0,0 +1,63 @@ +package p.studio.api.automation; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; + +/** Installed, owner-maintained knowledge. Authentication belongs to the calling adapter. */ +public interface ProjectKnowledge { + Context context(Path openProjectRoot); + ReferencePage readReference(Path openProjectRoot, String referenceId, int offset, int limit); + + record Version(String value, String source) { + public Version { + Objects.requireNonNull(source, "source"); + if (source.isBlank() || value != null && value.isBlank()) throw new IllegalArgumentException("Blank version provenance"); + } + public boolean known() { return value != null; } + public static Version unknown() { return new Version(null, "unknown"); } + } + enum Support { SUPPORTED, UNSUPPORTED, UNKNOWN } + record Capability(String name, Support support, String limitation) { + public Capability { Objects.requireNonNull(name); Objects.requireNonNull(support); } + } + record Language(String id, boolean primary, Version languageVersion, Version compilerVersion, + Version sdkVersion, List extensions, List sourceRoots, + List capabilities, List referenceIds) { + public Language { + Objects.requireNonNull(id); Objects.requireNonNull(languageVersion); + Objects.requireNonNull(compilerVersion); Objects.requireNonNull(sdkVersion); + extensions = List.copyOf(extensions); sourceRoots = List.copyOf(sourceRoots); + capabilities = List.copyOf(capabilities); referenceIds = List.copyOf(referenceIds); + } + } + enum ReferenceKind { QUICKSTART, SYNTAX, SEMANTICS, EXAMPLE, SDK, LIBRARY } + record Reference(String id, String title, String owner, ReferenceKind kind, Version version) { + public Reference { Objects.requireNonNull(id); Objects.requireNonNull(title); Objects.requireNonNull(owner); Objects.requireNonNull(kind); Objects.requireNonNull(version); } + } + record Library(String id, Version version, List roots, boolean editable) { + public Library { Objects.requireNonNull(id); Objects.requireNonNull(version); roots = List.copyOf(roots); } + } + record Context(Path projectRoot, String projectName, List languages, + List libraries, List editableRoots, List readOnlyRoots, + List references, List limitations) { + public Context { + projectRoot = Objects.requireNonNull(projectRoot).toAbsolutePath().normalize(); + Objects.requireNonNull(projectName); + languages = List.copyOf(languages); libraries = List.copyOf(libraries); + editableRoots = List.copyOf(editableRoots); readOnlyRoots = List.copyOf(readOnlyRoots); + references = List.copyOf(references); limitations = List.copyOf(limitations); + } + } + /** Offsets and limits count Unicode code points, not bytes or UTF-16 code units. */ + record ReferencePage(String referenceId, int offset, int total, Integer nextOffset, String text) { + public ReferencePage { + Objects.requireNonNull(referenceId); Objects.requireNonNull(text); + int count = text.codePointCount(0, text.length()); + if (offset < 0 || total < offset || count > total - offset + || (nextOffset == null && count != total - offset) + || (nextOffset != null && (nextOffset != offset + count || nextOffset >= total || count == 0))) + throw new IllegalArgumentException("Invalid reference page"); + } + } +} 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 new file mode 100644 index 00000000..6d04e1de --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/TrackedOperation.java @@ -0,0 +1,23 @@ +package p.studio.api.automation; + +import p.studio.api.operation.OperationSnapshot; +import p.studio.api.shipper.ShipperPrepareResult; +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) { + public TrackedOperation { + Objects.requireNonNull(operation); Objects.requireNonNull(clientRequestId); Objects.requireNonNull(progress); + if (clientRequestId.isBlank()) throw new IllegalArgumentException("Empty client request identity"); + if (buildResult != null && runtimeResult != null) throw new IllegalArgumentException("Mixed operation result kinds"); + } + /** Unknown progress stays null. Never infer completion from cancellation acknowledgement. */ + public record Progress(Long requestedFrames, Long completedFrames) { + public Progress { + if (requestedFrames != null && requestedFrames < 0 || completedFrames != null && completedFrames < 0 + || requestedFrames != null && completedFrames != null && completedFrames > requestedFrames) + throw new IllegalArgumentException("Invalid frame progress"); + } + } +} From 58f11a8123d5be8c867b2cb14bb47546048b4221 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 08:30:38 +0100 Subject: [PATCH 03/15] expose manifest-driven project knowledge through MCP --- ...CP Tools and Project Knowledge Contract.md | 51 +++- prometeu-app/build.gradle.kts | 1 + .../app/StudioApplicationConfiguration.java | 14 +- .../compiler/CompilerProjectKnowledge.java | 229 ++++++++++++++++++ .../app/mcp/McpProjectKnowledgeTools.java | 24 ++ .../p/studio/app/mcp/McpToolRegistry.java | 3 + .../StudioApplicationConfigurationTest.java | 4 +- .../CompilerProjectKnowledgeTest.java | 193 +++++++++++++++ .../p/studio/app/mcp/LocalMcpServerTest.java | 32 +++ .../api/automation/AutomationException.java | 15 ++ .../core/project/ProjectAccessRegistry.java | 34 ++- .../session/DefaultProjectSessionFactory.java | 5 +- .../project/ProjectAccessRegistryTest.java | 47 ++++ .../session/DefaultProjectSessionTest.java | 26 +- 14 files changed, 665 insertions(+), 13 deletions(-) create mode 100644 prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java create mode 100644 prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationException.java create mode 100644 prometeu-studio-core/src/test/java/p/studio/core/project/ProjectAccessRegistryTest.java 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 ffc75335..01a30573 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 @@ -186,6 +186,54 @@ points. A page returns referenceId, offset, total, text and nextOffset (null at end). Invalid pagination fails; unknown/traversal-like IDs cannot escape the index. Installed packaging and real provider resolution are steps 17–18. +### 5.1 Manifest and Provider Resolution + +`studio_project_context` resolves an exact, canonical root registered by an open +project session. It does not use the focused window, accept a source-directory +path as a project root, acquire a manual lease, or require an AI grant. A session +is discoverable only after successful opening and until closure begins. +Unregistered/closed roots return `PROJECT_NOT_OPEN`. + +Each call reads the saved `prometeu.json` and dependency manifests again. Missing +or invalid primary manifests fail explicitly instead of returning cached language +metadata. Languages are grouped by declared ID, with the primary flag derived +from the main manifest. Unknown IDs retain their identity and expose unsupported +build/LSP support; no default frontend is consulted. + +Extensions and source roots come from the installed frontend specification. +LSP feature support comes from the same compiler bridge description used by the +existing LSP server, not from a duplicated PBS capability list. If that provider +cannot describe its LSP, support is UNKNOWN with an explicit limitation. These +are installed-provider capabilities, not a promise that the MCP language-query +tool is already composed or that any particular source file will compile. + +Language versions remain unknown when no owner metadata exists. Compiler versions +use the installed frontend package's `Implementation-Version` only when present. +The requested SDK version has manifest provenance; the context distinguishes +versions supported by the installed provider from unsupported requests. Multiple +SDK requests for the same language yield an unknown aggregate version, an explicit +limitation and separate SDK library entries. These identifiers MUST NOT be +substituted for one another. + +Dependency paths and registry entries use the compiler's existing resolver, +including its main-root-relative local path semantics and registry requirement. +Discovery does not create a registry, install dependencies or build sources. +Unresolved declarations remain visible with empty roots and limitations. Mixed +language graphs are described but reported as unsupported for the current build +pipeline. Discovery is bounded to 256 projects and 256 declarations per manifest. + +The editable scope is the canonical project root **minus** read-only roots. +Read-only scope takes precedence: external/registry libraries and their transitive +dependencies remain protected even when stored beneath the project root or also +reachable through a local declaration. Source roots are canonicalized, including +symlink targets. SDK entries are always read-only; packaged SDK resources need not +have filesystem roots. Scope metadata does not sandbox an external agent's own +filesystem tools; the developer remains responsible for those tools and Git. + +Paths in MCP results are absolute filesystem strings, not `file:` URIs. Until +step 18 packages the owner-maintained index, references/reference IDs are empty +with `DOCUMENTATION_UNAVAILABLE`; no guessed path or reference is advertised. + ## 6. Image Contract MCP image content has `type:image`, `mimeType:image/png`, and base64 `data` of @@ -210,7 +258,8 @@ authentication, Origin, endpoint/method/version handling, tool dispatch, malform or oversized input, closure, restart and old-token rejection. Provider doubles exist only in tests. Composition starts/closes transport with Studio. -Step 16's production registry is empty until functional handlers are composed; +The production registry composes `studio_project_context` as of step 17; other +tools are advertised only when their functional handlers are connected. 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/build.gradle.kts b/prometeu-app/build.gradle.kts index 1c17f60e..76bb1cf0 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -10,6 +10,7 @@ dependencies { implementation(project(":prometeu-compiler:prometeu-compiler-core")) implementation(project(":prometeu-compiler:prometeu-build-pipeline")) implementation(project(":prometeu-compiler:prometeu-frontend-registry")) + implementation(project(":prometeu-compiler:prometeu-deps")) implementation(project(":prometeu-packer:prometeu-packer-api")) implementation(project(":prometeu-packer:prometeu-packer-v1")) implementation(project(":prometeu-studio-api")) 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 dbfe0ec8..cd1c1765 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -296,9 +296,17 @@ public class StudioApplicationConfiguration { } @Bean - p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper) { - // Providers are connected in PLN-0139 steps 17–20. Never advertise placeholders. - return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, java.util.Map.of()); + p.studio.api.automation.ProjectKnowledge projectKnowledge( + p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper) { + return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper); + } + + @Bean + p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper, + p.studio.api.automation.ProjectKnowledge knowledge) { + // Further providers are connected in PLN-0139 steps 18–20. Never advertise placeholders. + return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, + p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper)); } @Bean(initMethod = "start", destroyMethod = "close") diff --git a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java new file mode 100644 index 00000000..36227164 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java @@ -0,0 +1,229 @@ +package p.studio.app.compiler; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.AutomationException; +import p.studio.api.automation.AutomationFailure; +import p.studio.api.automation.ProjectKnowledge; +import p.studio.api.project.ProjectCatalog; +import p.studio.api.project.ProjectReference; +import p.studio.compiler.FrontendRegistryService; +import p.studio.compiler.dtos.PrometeuManifestDTO; +import p.studio.compiler.messages.BuildingIssueSink; +import p.studio.compiler.workspaces.phases.DependencyResolver; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.lsp.messages.LspProjectContext; +import p.studio.lsp.services.compiler.CompilerLanguageServiceBridge; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.*; + +/** Read-only manifest/provider discovery. Never selects a default frontend or starts a build. */ +public final class CompilerProjectKnowledge implements ProjectKnowledge { + private static final int MAX_PROJECTS = 256; + private final ProjectAccessRegistry openProjects; + private final ProjectCatalog projects; + private final ObjectMapper mapper; + private final CompilerLanguageServiceBridge languageBridge = new CompilerLanguageServiceBridge(); + + public CompilerProjectKnowledge(ProjectAccessRegistry openProjects, ProjectCatalog projects, ObjectMapper mapper) { + this.openProjects = Objects.requireNonNull(openProjects); + this.projects = Objects.requireNonNull(projects); + this.mapper = Objects.requireNonNull(mapper); + } + + @Override public Context context(Path openProjectRoot) { + Path root = openProjects.requireOpenRoot(openProjectRoot); + var limitations = new ArrayList(); + var discovered = new LinkedHashMap(); + var dependencies = new LinkedHashMap>(); + var readOnly = new LinkedHashSet(); + var unresolved = new ArrayList(); + var pending = new ArrayDeque(); + var visited = new HashSet(); + pending.add(root); + boolean dependenciesComplete = true; + while (!pending.isEmpty()) { + Path current = pending.removeFirst(); + if (!visited.add(current)) continue; + if (visited.size() > MAX_PROJECTS) + throw new AutomationException(AutomationFailure.Code.LIMIT_EXCEEDED, "Project graph exceeds " + MAX_PROJECTS + " projects"); + ProjectReference project; + PrometeuManifestDTO manifest; + try { + project = projects.openProject(current); + manifest = mapper.readValue(current.resolve("prometeu.json").toFile(), PrometeuManifestDTO.class); + } catch (IOException | RuntimeException failure) { + if (current.equals(root)) + throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Cannot read the current project manifest"); + dependenciesComplete = false; + limitations.add("Dependency manifest unavailable: " + current); + unresolved.add(new Library(current.toString(), Version.unknown(), List.of(current), false)); + readOnly.add(current); + dependencies.put(current, List.of()); + continue; + } + discovered.put(current, project); + var children = new ArrayList(); + dependencies.put(current, children); + if (manifest.dependencies() == null) continue; + if (manifest.dependencies().size() > MAX_PROJECTS) + throw new AutomationException(AutomationFailure.Code.LIMIT_EXCEEDED, "Too many dependency declarations"); + for (var declaration : manifest.dependencies()) { + if (declaration == null + || declaration instanceof PrometeuManifestDTO.DependencyDeclaration.Local local + && (local.path() == null || local.path().isBlank()) + || declaration instanceof PrometeuManifestDTO.DependencyDeclaration.Registry registry + && (registry.name() == null || registry.name().isBlank() || registry.version() == null || registry.version().isBlank())) + throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Invalid dependency declaration in " + current); + var issues = BuildingIssueSink.empty(); + // The compiler resolves even transitive local paths and registry entries against the main root. + var resolved = DependencyResolver.resolveDependencies(root, List.of(declaration), issues); + if (issues.hasErrors() || resolved.isEmpty()) { + dependenciesComplete = false; + String id = declaration instanceof PrometeuManifestDTO.DependencyDeclaration.Registry registry + ? registry.name() + "@" + registry.version() + : String.valueOf(((PrometeuManifestDTO.DependencyDeclaration.Local) declaration).path()); + var version = declaration instanceof PrometeuManifestDTO.DependencyDeclaration.Registry registry + && registry.version() != null && !registry.version().isBlank() + ? new Version(registry.version(), current.resolve("prometeu.json") + "#dependencies (requested)") : Version.unknown(); + unresolved.add(new Library(id, version, List.of(), false)); + limitations.add("Dependency could not be resolved by the compiler: " + id + " (declared by " + current + ")"); + continue; + } + Path child = resolved.getFirst().canonPath(); + children.add(child); + if (!child.startsWith(root) || declaration instanceof PrometeuManifestDTO.DependencyDeclaration.Registry) + readOnly.add(child); + pending.add(child); + } + } + // Read-only provenance wins if a library is reachable through more than one declaration. + boolean changed; + do { + changed = false; + for (var edge : dependencies.entrySet()) + if (readOnly.stream().anyMatch(edge.getKey()::startsWith)) + changed |= readOnly.addAll(edge.getValue()); + } while (changed); + + var protectedSources = new LinkedHashSet(); + for (var project : discovered.values()) { + if (readOnly.stream().anyMatch(project.rootPath()::startsWith)) + FrontendRegistryService.getProvider(project.languageId()).ifPresent(provider -> + provider.specification().getSourceRoots().forEach(relative -> + protectedSources.add(canonical(project.rootPath().resolve(relative))))); + } + readOnly.addAll(protectedSources); + + var libraries = new ArrayList(); + var byLanguage = new LinkedHashMap>(); + for (var entry : discovered.entrySet()) { + var project = entry.getValue(); + byLanguage.computeIfAbsent(project.languageId(), ignored -> new ArrayList<>()).add(project); + if (!entry.getKey().equals(root)) { + boolean editable = entry.getKey().startsWith(root) && readOnly.stream().noneMatch(entry.getKey()::startsWith); + libraries.add(new Library(project.name(), new Version(project.version(), entry.getKey().resolve("prometeu.json") + "#version"), + List.of(entry.getKey()), editable)); + } + } + libraries.addAll(unresolved); + var languages = new ArrayList(); + String primary = discovered.get(root).languageId(); + if (byLanguage.size() > 1) limitations.add("The installed build pipeline requires the same language across the dependency graph"); + for (var entry : byLanguage.entrySet()) { + var language = language(entry.getKey(), entry.getValue(), primary.equals(entry.getKey()), + dependenciesComplete && byLanguage.size() == 1, limitations); + languages.add(language); + for (Path source : language.sourceRoots()) if (!source.startsWith(root)) readOnly.add(source); + for (var project : entry.getValue()) { + var sdk = new Library("sdk:" + entry.getKey() + ":" + project.stdlibVersion(), + new Version(Integer.toString(project.stdlibVersion()), project.rootPath().resolve("prometeu.json") + "#stdlib (requested)"), + List.of(), false); + if (libraries.stream().noneMatch(item -> item.id().equals(sdk.id()))) libraries.add(sdk); + } + } + limitations.add("SDK resources are provider-owned, read-only resources, not editable project files"); + limitations.add("DOCUMENTATION_UNAVAILABLE: installed language/SDK reference index is not yet available"); + // Closing a project during discovery must not publish a successful context for that closed project. + openProjects.requireOpenRoot(root); + return new Context(root, discovered.get(root).name(), languages, libraries, + List.of(root), List.copyOf(readOnly), List.of(), limitations); + } + + private Language language(String id, List projects, boolean primary, + boolean graphBuildable, List limitations) { + var sdkVersions = projects.stream().map(ProjectReference::stdlibVersion).distinct().toList(); + Version sdk = sdkVersions.size() == 1 + ? new Version(sdkVersions.getFirst().toString(), "prometeu.json#stdlib (requested)") : Version.unknown(); + if (sdkVersions.size() != 1) limitations.add("Multiple SDK versions requested for " + id + ": " + sdkVersions); + var provider = FrontendRegistryService.getProvider(id); + if (provider.isEmpty()) { + limitations.add("UNSUPPORTED_LANGUAGE: no installed frontend for " + id); + return new Language(id, primary, Version.unknown(), Version.unknown(), sdk, List.of(), List.of(), + List.of(capability("build", false), capability("lsp", false)), List.of()); + } + var spec = provider.get().specification(); + var roots = new LinkedHashSet(); + projects.forEach(project -> spec.getSourceRoots().forEach(relative -> roots.add(canonical(project.rootPath().resolve(relative))))); + boolean sdkSupported = sdkVersions.stream().allMatch(version -> spec.getStdlibVersions().stream().anyMatch(item -> item.version() == version)); + if (!sdkSupported) limitations.add("Unsupported requested SDK version for " + id + ": " + sdkVersions); + if (sdkSupported && sdk.known()) sdk = new Version(sdk.value(), "prometeu.json#stdlib; supported by installed frontend"); + var capabilities = new ArrayList(); + capabilities.add(capability("build", graphBuildable && sdkSupported)); + var project = projects.getFirst(); + addLspCapabilities(id, project, capabilities, limitations); + String compilerVersion = provider.get().getClass().getPackage().getImplementationVersion(); + return new Language(id, primary, Version.unknown(), compilerVersion == null || compilerVersion.isBlank() + ? Version.unknown() : new Version(compilerVersion, "installed frontend package Implementation-Version"), sdk, + spec.getAllowedExtensions().stream().sorted().toList(), List.copyOf(roots), capabilities, List.of()); + } + + private void addLspCapabilities(String id, ProjectReference project, List capabilities, List limitations) { + final p.studio.lsp.messages.BaselineServerDescription server; + try { + server = languageBridge.describeServer(new LspProjectContext(project.rootPath().toString(), id, project.rootPath())); + } catch (RuntimeException unavailable) { + String reason = "Installed frontend cannot describe LSP capabilities for " + id; + capabilities.add(new Capability("lsp", Support.UNKNOWN, reason)); + limitations.add(reason); + return; + } + capabilities.add(capability("lsp", true)); + capabilities.add(capability("diagnostics", true)); + capabilities.add(capability("hover", server.hoverSupported())); + capabilities.add(capability("completion", server.completionSupported())); + capabilities.add(capability("signatureHelp", server.signatureHelpSupported())); + capabilities.add(capability("definition", server.definitionSupported())); + capabilities.add(capability("references", server.referencesSupported())); + capabilities.add(capability("documentSymbols", server.documentSymbolsSupported())); + capabilities.add(capability("workspaceSymbols", server.workspaceSymbolsSupported())); + capabilities.add(capability("rename", server.renameSupported())); + capabilities.add(capability("codeActions", server.codeActionsSupported())); + capabilities.add(capability("documentLinks", server.documentLinksSupported())); + capabilities.add(capability("foldingRanges", server.foldingRangesSupported())); + capabilities.add(capability("selectionRanges", server.selectionRangesSupported())); + capabilities.add(capability("formatting", server.formattingSupported())); + capabilities.add(capability("callHierarchy", server.callHierarchySupported())); + capabilities.add(capability("typeHierarchy", false)); + } + + private static Capability capability(String name, boolean supported) { + return new Capability(name, supported ? Support.SUPPORTED : Support.UNSUPPORTED, + supported ? null : "Not supported by the installed provider or current project dependency/SDK configuration"); + } + + private static Path canonical(Path path) { + Path normalized = path.toAbsolutePath().normalize(); + try { return normalized.toRealPath(); } + catch (IOException ignored) { + Path parent = normalized.getParent(); + return parent == null ? normalized : canonical(parent).resolve(normalized.getFileName()); + } + } + + @Override public ReferencePage readReference(Path openProjectRoot, String referenceId, int offset, int limit) { + openProjects.requireOpenRoot(openProjectRoot); + throw new AutomationException(AutomationFailure.Code.DOCUMENTATION_UNAVAILABLE, "No installed reference index is available"); + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java new file mode 100644 index 00000000..24ca17d3 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java @@ -0,0 +1,24 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import p.studio.api.automation.ProjectKnowledge; + +import java.nio.file.Path; +import java.util.Map; +import java.util.function.Function; + +/** Context reads need authentication at transport level, but no control grant or task. */ +public final class McpProjectKnowledgeTools { + private McpProjectKnowledgeTools() {} + + public static Map> handlers(ProjectKnowledge knowledge, ObjectMapper mapper) { + // Jackson's default Path serializer produces file: URIs; the public contract uses absolute paths. + var paths = new SimpleModule().addSerializer(Path.class, new ToStringSerializer()); + var wireMapper = mapper.copy().registerModule(paths); + return Map.of("studio_project_context", arguments -> McpToolResult.success(mapper, + wireMapper.valueToTree(knowledge.context(Path.of(arguments.path("projectRoot").asText()))))); + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java index 48ce2b35..0849ab02 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java @@ -27,6 +27,9 @@ public final class McpToolRegistry { if (handler == null) throw new IllegalArgumentException("Unknown or unavailable tool"); catalog.validateArguments(name, arguments); try { return handler.apply(arguments); } + catch (p.studio.api.automation.AutomationException failure) { + return McpToolResult.failure(mapper, failure.failure()); + } catch (ControlDeniedException denied) { var code = switch (denied.status()) { case INVALID_TASK -> AutomationFailure.Code.INVALID_TASK; 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 d9063b9e..3bfd4033 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -29,7 +29,9 @@ class StudioApplicationConfigurationTest { assertFalse(context.getClass().getName().contains("WebServer")); assertFalse(executor.isShutdown()); assertTrue(mcp.isRunning()); - assertTrue(context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors().isEmpty()); + var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors(); + org.junit.jupiter.api.Assertions.assertEquals(1, tools.size()); + org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText()); } assertTrue(executor.isShutdown()); assertFalse(mcp.isRunning()); diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java new file mode 100644 index 00000000..f9aeb9f8 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java @@ -0,0 +1,193 @@ +package p.studio.app.compiler; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.compiler.FrontendRegistryService; +import p.studio.compiler.models.FrontendSpec; +import p.studio.compiler.services.FrontendPhaseService; +import p.studio.compiler.services.FrontendProvider; +import p.studio.core.project.*; +import p.studio.utilities.structures.ReadOnlySet; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +class CompilerProjectKnowledgeTest { + @TempDir Path directory; + final ObjectMapper mapper = new ObjectMapper(); + final ProjectAccessRegistry access = new ProjectAccessRegistry(); + + CompilerProjectKnowledge knowledge() { + return new CompilerProjectKnowledge(access, + new ProjectCatalogService(directory, mapper, new ProjectLocalStudioSetupStore(mapper)), mapper); + } + + @Test void pbsContextIsReadOnlyManifestDrivenAndVersionsAreIndependent() throws Exception { + Path root = project("game", "pbs", "1", "[]"); + access.register(root, () -> { throw new AssertionError("No grant needed"); }, () -> true); + var result = knowledge().context(root); + var language = result.languages().getFirst(); + assertEquals("pbs", language.id()); + assertTrue(language.primary()); + assertEquals(List.of("barrel", "pbs"), language.extensions()); + assertEquals(List.of(root.resolve("src")), language.sourceRoots()); + assertFalse(language.languageVersion().known()); + assertFalse(language.compilerVersion().known()); + assertEquals("1", language.sdkVersion().value()); + assertTrue(language.sdkVersion().source().contains("supported by installed")); + assertSupport(language, "build", ProjectKnowledge.Support.SUPPORTED); + assertSupport(language, "definition", ProjectKnowledge.Support.SUPPORTED); + assertSupport(language, "typeHierarchy", ProjectKnowledge.Support.UNSUPPORTED); + assertEquals(List.of(root), result.editableRoots()); + assertFalse(result.libraries().getFirst().editable()); + assertTrue(result.libraries().getFirst().id().startsWith("sdk:pbs:")); + assertTrue(result.references().isEmpty()); + assertTrue(result.limitations().stream().anyMatch(value -> value.contains("DOCUMENTATION_UNAVAILABLE"))); + assertFalse(Files.exists(root.resolve(".workspace"))); + assertFalse(Files.exists(root.resolve(".studio"))); + } + + @Test void rereadsSavedManifestAndNeverFallsBackForAnUnknownLanguageOrSdk() throws Exception { + Path root = project("game", "pbs", "1", "[]"); + var registration = access.register(root, () -> () -> {}, () -> true); + var knowledge = knowledge(); + assertEquals("pbs", knowledge.context(root).languages().getFirst().id()); + project("game", "missing-language", "9", "[]"); + var unknown = knowledge.context(root).languages().getFirst(); + assertEquals("missing-language", unknown.id()); + assertTrue(unknown.extensions().isEmpty()); + assertTrue(unknown.sourceRoots().isEmpty()); + assertSupport(unknown, "build", ProjectKnowledge.Support.UNSUPPORTED); + assertEquals("9", unknown.sdkVersion().value()); + assertTrue(unknown.sdkVersion().source().contains("requested")); + project("game", "pbs", "999", "[]"); + assertSupport(knowledge.context(root).languages().getFirst(), "build", ProjectKnowledge.Support.UNSUPPORTED); + registration.unsubscribe(); + assertEquals(AutomationFailure.Code.PROJECT_NOT_OPEN, + assertThrows(AutomationException.class, () -> knowledge.context(root)).failure().code()); + } + + @Test void alternateInstalledMetadataUsesItsOwnExtensionsSdkAndLspCapabilitiesWithoutCompiling() throws Exception { + String id = "context-test-language"; + FrontendRegistryService.register(new FrontendProvider() { + @Override public FrontendSpec specification() { + return FrontendSpec.builder().languageId(id).allowedExtensions(ReadOnlySet.from("alt")) + .sourceRoots(ReadOnlySet.from("code")).stdlibVersions(List.of(FrontendSpec.Stdlib.asDefault(7))) + // Reuse only a visual-theme fixture; no PBS compiler or language service is installed for this ID. + .semanticPresentation(FrontendRegistryService.require("pbs").specification().getSemanticPresentation()).build(); + } + @Override public FrontendPhaseService compiler() { throw new AssertionError("Discovery must not compile"); } + }); + try { + Path root = project("alternate", id, "7", "[]"); + access.register(root, () -> () -> {}, () -> true); + var language = knowledge().context(root).languages().getFirst(); + assertEquals(id, language.id()); + assertEquals(List.of("alt"), language.extensions()); + assertEquals(List.of(root.resolve("code")), language.sourceRoots()); + assertEquals("7", language.sdkVersion().value()); + assertSupport(language, "build", ProjectKnowledge.Support.SUPPORTED); + assertSupport(language, "definition", ProjectKnowledge.Support.UNSUPPORTED); + assertSupport(language, "formatting", ProjectKnowledge.Support.UNSUPPORTED); + assertFalse(language.languageVersion().known()); + } finally { FrontendRegistryService.unregister(id); } + } + + @Test void localExternalRegistryAndSymlinkLibrariesHaveCanonicalScopes() throws Exception { + Path root = project("game", "pbs", "1", """ + [{"path":"lib"},{"path":"external-alias"},{"name":"registered","version":"1.0.0"}] + """); + Path local = project("game/lib", "pbs", "1", "[]"); + Path external = project("external", "pbs", "1", "[]"); + Path registered = project("game/vendor", "pbs", "1", "[]"); + Files.createSymbolicLink(root.resolve("external-alias"), external); + Files.createDirectories(root.resolve(".workspace/repos")); + mapper.writeValue(root.resolve(".workspace/repos/registry.json").toFile(), java.util.Map.of("registered@1.0.0", registered.toString())); + access.register(root, () -> () -> {}, () -> true); + var result = knowledge().context(root); + assertTrue(library(result, local).editable()); + assertFalse(library(result, external).editable()); + assertFalse(library(result, registered).editable()); + assertTrue(result.readOnlyRoots().contains(external)); + assertTrue(result.readOnlyRoots().contains(registered)); + } + + @Test void externalSourceRootsAreReadOnlyAndUnresolvedDependenciesAreVisible() throws Exception { + Path root = project("game", "pbs", "1", "[{\"path\":\"missing\"}]"); + Path externalSources = Files.createDirectory(directory.resolve("external-sources")).toRealPath(); + Files.createSymbolicLink(root.resolve("src"), externalSources); + access.register(root, () -> () -> {}, () -> true); + var result = knowledge().context(root); + assertTrue(result.readOnlyRoots().contains(externalSources)); + assertTrue(result.libraries().stream().anyMatch(library -> library.id().equals("missing") && library.roots().isEmpty() && !library.editable())); + assertSupport(result.languages().getFirst(), "build", ProjectKnowledge.Support.UNSUPPORTED); + assertTrue(result.limitations().stream().anyMatch(value -> value.contains("could not be resolved"))); + assertFalse(Files.exists(root.resolve(".workspace"))); + } + + @Test void invalidOrMissingManifestIsATypedFailureNotAStaleContext() throws Exception { + Path root = project("game", "pbs", "1", "[]"); + access.register(root, () -> () -> {}, () -> true); + Files.writeString(root.resolve("prometeu.json"), "{}"); + assertEquals(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, + assertThrows(AutomationException.class, () -> knowledge().context(root)).failure().code()); + Files.delete(root.resolve("prometeu.json")); + assertEquals(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, + assertThrows(AutomationException.class, () -> knowledge().context(root)).failure().code()); + } + + @Test void transitiveReadOnlyProvenanceWinsAndMixedLanguagesRemainVisible() throws Exception { + Path root = project("game", "pbs", "1", "[{\"path\":\"lib\"},{\"path\":\"../external\"}]"); + Path local = project("game/lib", "pbs", "1", "[]"); + Path external = project("external", "unknown-language", "2", "[{\"path\":\"lib\"}]"); + Files.createDirectories(root.resolve(".workspace/repos")); + Files.writeString(root.resolve(".workspace/repos/registry.json"), "{}"); + access.register(root, () -> () -> {}, () -> true); + var result = knowledge().context(root); + assertFalse(library(result, local).editable()); + assertFalse(library(result, external).editable()); + assertTrue(result.readOnlyRoots().contains(local.resolve("src"))); + assertEquals(List.of("pbs", "unknown-language"), result.languages().stream().map(ProjectKnowledge.Language::id).toList()); + assertFalse(result.languages().get(1).primary()); + assertSupport(result.languages().getFirst(), "build", ProjectKnowledge.Support.UNSUPPORTED); + } + + @Test void incompleteInstalledLspMetadataReportsUnknownInsteadOfInventingCapabilities() throws Exception { + String id = "incomplete-test-language"; + FrontendRegistryService.register(new FrontendProvider() { + @Override public FrontendSpec specification() { + return FrontendSpec.builder().languageId(id).allowedExtensions(ReadOnlySet.from("alt")) + .sourceRoots(ReadOnlySet.from("code")).build(); + } + @Override public FrontendPhaseService compiler() { throw new AssertionError("Discovery must not compile"); } + }); + try { + Path root = project("alternate", id, "1", "[]"); + access.register(root, () -> () -> {}, () -> true); + var result = knowledge().context(root); + assertSupport(result.languages().getFirst(), "lsp", ProjectKnowledge.Support.UNKNOWN); + assertTrue(result.limitations().stream().anyMatch(value -> value.contains("cannot describe LSP"))); + } finally { FrontendRegistryService.unregister(id); } + } + + private Path project(String name, String language, String sdk, String dependencies) throws Exception { + Path root = Files.createDirectories(directory.resolve(name)).toRealPath(); + var manifest = mapper.createObjectNode().put("name", name).put("version", "1.0.0") + .put("language", language).put("stdlib", sdk).put("target", "Game"); + manifest.set("dependencies", mapper.readTree(dependencies)); + mapper.writeValue(root.resolve("prometeu.json").toFile(), manifest); + return root; + } + + private ProjectKnowledge.Library library(ProjectKnowledge.Context context, Path root) { + return context.libraries().stream().filter(library -> library.roots().contains(root)).findFirst().orElseThrow(); + } + + private void assertSupport(ProjectKnowledge.Language language, String name, ProjectKnowledge.Support support) { + assertEquals(support, language.capabilities().stream().filter(capability -> capability.name().equals(name)).findFirst().orElseThrow().support()); + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java index b2c14105..6db162f0 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java @@ -103,6 +103,38 @@ class LocalMcpServerTest { assertTrue(result.path("isError").asBoolean()); assertEquals("NOT_GRANTED", result.path("structuredContent").path("error").path("code").asText()); } + @Test void realContextHandlerReadsAnOpenProjectWithoutGrantAndRejectsItAfterClose( + @org.junit.jupiter.api.io.TempDir java.nio.file.Path temporary) throws Exception { + var root = temporary.toRealPath(); + java.nio.file.Files.writeString(root.resolve("prometeu.json"), """ + {"name":"HTTP context","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + var open = new p.studio.core.project.ProjectAccessRegistry(); + var registration = open.register(root, () -> { throw new AssertionError("Context must not acquire manual control"); }, () -> true); + var catalog = new p.studio.core.project.ProjectCatalogService(root, mapper, + new p.studio.core.project.ProjectLocalStudioSetupStore(mapper)); + var knowledge = new p.studio.app.compiler.CompilerProjectKnowledge(open, catalog, mapper); + server.close(); + server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, + McpProjectKnowledgeTools.handlers(knowledge, mapper))); + server.start(); + initialize(); + var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call"); + call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", root.toString()); + var wire = mapper.readTree(post(call.toString()).body()).path("result"); + assertFalse(wire.path("isError").asBoolean()); + var value = wire.path("structuredContent").path("value"); + assertEquals(root.toString(), value.path("projectRoot").asText()); + assertEquals(root.toString(), value.path("editableRoots").get(0).asText()); + assertEquals("pbs", value.path("languages").get(0).path("id").asText()); + assertTrue(value.path("languages").get(0).path("languageVersion").path("value").isNull()); + assertFalse(java.nio.file.Files.exists(root.resolve(".studio"))); + registration.unsubscribe(); + var denied = mapper.readTree(post(call.toString()).body()).path("result"); + assertTrue(denied.path("isError").asBoolean()); + assertEquals("PROJECT_NOT_OPEN", denied.path("structuredContent").path("error").path("code").asText()); + } + @Test void hostileHostAndDuplicateOriginAreRejectedEvenWithValidCredentials() throws Exception { var connection = server.connection(); try (var socket = new java.net.Socket("127.0.0.1", connection.endpoint().getPort())) { diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationException.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationException.java new file mode 100644 index 00000000..5d2cc787 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationException.java @@ -0,0 +1,15 @@ +package p.studio.api.automation; + +import java.util.Objects; + +/** Expected service failure, independent of the transport used by an automation client. */ +public final class AutomationException extends IllegalStateException { + private final AutomationFailure failure; + + public AutomationException(AutomationFailure.Code code, String message) { + super(message); + failure = new AutomationFailure(Objects.requireNonNull(code), message); + } + + public AutomationFailure failure() { return failure; } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java index 4b5748a9..555e5f0c 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java @@ -8,15 +8,39 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; +import java.util.function.BooleanSupplier; +import p.studio.api.automation.AutomationException; +import p.studio.api.automation.AutomationFailure; /** Application-composed routing only; authority is owned by each project session. */ public final class ProjectAccessRegistry implements ProjectAccess { - private final Map> projects = new HashMap<>(); + private record Entry(Supplier authority, BooleanSupplier available) {} + private final Map projects = new HashMap<>(); - public synchronized OperationSubscription register(Path root, Supplier authority) { + public OperationSubscription register(Path root, Supplier authority) { + return register(root, authority, () -> false); + } + + public synchronized OperationSubscription register(Path root, Supplier authority, BooleanSupplier available) { Path key = canonical(root); - if (projects.putIfAbsent(key, authority) != null) throw new IllegalStateException("Project already open: " + key); - return () -> { synchronized (this) { projects.remove(key, authority); } }; + var entry = new Entry(java.util.Objects.requireNonNull(authority), java.util.Objects.requireNonNull(available)); + if (projects.putIfAbsent(key, entry) != null) throw new IllegalStateException("Project already open: " + key); + return () -> { synchronized (this) { projects.remove(key, entry); } }; + } + + /** Exact root lookup, never focus-based or a descendant-path admission. No grant is needed. */ + public Path requireOpenRoot(Path root) { + Path key = canonical(root); + Entry entry; + synchronized (this) { entry = projects.get(key); } + // Never call session code while holding the routing lock. + if (!root.isAbsolute() || entry == null || !entry.available().getAsBoolean()) + throw new AutomationException(AutomationFailure.Code.PROJECT_NOT_OPEN, "The explicit project root is not open"); + synchronized (this) { + if (projects.get(key) != entry) + throw new AutomationException(AutomationFailure.Code.PROJECT_NOT_OPEN, "The project was closed"); + } + return key; } @Override public ManualLease enterManual(Path path) { @@ -25,7 +49,7 @@ public final class ProjectAccessRegistry implements ProjectAccess { Path key = canonical(path); authority = projects.entrySet().stream().filter(e -> key.startsWith(e.getKey())) .max(java.util.Comparator.comparingInt(e -> e.getKey().getNameCount())) - .map(Map.Entry::getValue).orElse(null); + .map(e -> e.getValue().authority()).orElse(null); } // Project creation/setup before opening a session is still a manual workflow. return authority == null ? () -> {} : authority.get(); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index 627337b3..3cf66f3d 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -32,9 +32,12 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory final var setup = setupStore.load(project); final var state = stateStore.load(project); var automation = new DefaultAutomationSession(project.rootPath(), operations); - var registration = access.register(project.rootPath(), automation::enterManual); + var ready = new java.util.concurrent.atomic.AtomicBoolean(); + var registration = access.register(project.rootPath(), automation::enterManual, + () -> ready.get() && !automation.snapshot().closed()); try { lsp.boot(project); } catch (RuntimeException failure) { registration.unsubscribe(); throw failure; } + ready.set(true); return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, registration); } } diff --git a/prometeu-studio-core/src/test/java/p/studio/core/project/ProjectAccessRegistryTest.java b/prometeu-studio-core/src/test/java/p/studio/core/project/ProjectAccessRegistryTest.java new file mode 100644 index 00000000..38e688fd --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/project/ProjectAccessRegistryTest.java @@ -0,0 +1,47 @@ +package p.studio.core.project; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.AutomationException; +import p.studio.api.automation.AutomationFailure; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicBoolean; +import static org.junit.jupiter.api.Assertions.*; + +class ProjectAccessRegistryTest { + @TempDir Path root; + + @Test void exactOpenRootsIgnoreFocusAndDoNotAcquireManualAuthority() throws Exception { + var registry = new ProjectAccessRegistry(); + Path first = Files.createDirectory(root.resolve("first")).toRealPath(); + Path second = Files.createDirectory(root.resolve("second")).toRealPath(); + var available = new AtomicBoolean(true); + var registration = registry.register(first, () -> { throw new AssertionError("Context does not acquire control"); }, available::get); + registry.register(second, () -> () -> {}, () -> true); + assertEquals(first, registry.requireOpenRoot(first)); + assertEquals(second, registry.requireOpenRoot(second)); + assertDenied(registry, first.resolve("src")); + assertDenied(registry, Path.of("relative")); + var alias = Files.createSymbolicLink(root.resolve("alias"), first); + assertEquals(first, registry.requireOpenRoot(alias)); + available.set(false); + assertDenied(registry, first); + available.set(true); + registration.unsubscribe(); + assertDenied(registry, first); + assertEquals(second, registry.requireOpenRoot(second)); + } + + @Test void guardOnlyRegistrationIsNotAnOpenProject() { + var registry = new ProjectAccessRegistry(); + registry.register(root, () -> () -> {}); + assertDenied(registry, root); + assertNotNull(registry.enterManual(root.resolve("src"))); + } + + private void assertDenied(ProjectAccessRegistry registry, Path path) { + assertEquals(AutomationFailure.Code.PROJECT_NOT_OPEN, + assertThrows(AutomationException.class, () -> registry.requireOpenRoot(path)).failure().code()); + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java index f80b95d0..864b04fc 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java @@ -17,21 +17,24 @@ final class DefaultProjectSessionTest { @TempDir Path temporaryDirectory; @Test - void factoryLoadsStateBootsLspAndCloseIsOrderedAndIdempotent() { + void factoryLoadsStateBootsLspAndCloseIsOrderedAndIdempotent() throws Exception { final var mapper = new ObjectMapper(); final var stateStore = new ProjectLocalStudioStateStore(mapper); final var setupStore = new ProjectLocalStudioSetupStore(mapper); final var lsp = new RecordingLsp(); + final var access = new p.studio.core.project.ProjectAccessRegistry(); final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp, - new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations()); + access, new p.studio.core.support.ControlledOperations()); final var project = project(); final var session = factory.open(project); + assertEquals(project.rootPath().toRealPath(), access.requireOpenRoot(project.rootPath())); final var next = ProjectLocalStudioState.defaults() .withOpenShellState(new ProjectLocalStudioState.OpenShellState("DEBUG")); session.replaceProjectLocalStudioState(next); session.close(); session.close(); + assertThrows(p.studio.api.automation.AutomationException.class, () -> access.requireOpenRoot(project.rootPath())); assertEquals(1, lsp.boots); assertEquals(1, lsp.shutdowns); @@ -55,6 +58,25 @@ final class DefaultProjectSessionTest { return new ProjectReference("Example", "1.0.0", "pbs", 1, ProjectTarget.Game, temporaryDirectory); } + @Test + void failedBootNeverPublishesAnOpenProjectAndRemovesItsRegistration() { + var mapper = new ObjectMapper(); + var access = new p.studio.core.project.ProjectAccessRegistry(); + var lsp = new LspLifecyclePort() { + @Override public void boot(ProjectReference project) { + assertThrows(p.studio.api.automation.AutomationException.class, () -> access.requireOpenRoot(project.rootPath())); + throw new IllegalStateException("boot failed"); + } + @Override public void shutdown(ProjectReference project) {} + }; + var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), + new ProjectLocalStudioSetupStore(mapper), lsp, access, new p.studio.core.support.ControlledOperations()); + assertThrows(IllegalStateException.class, () -> factory.open(project())); + assertThrows(p.studio.api.automation.AutomationException.class, () -> access.requireOpenRoot(project().rootPath())); + var registration = access.register(project().rootPath(), () -> () -> {}, () -> true); + registration.unsubscribe(); + } + private static final class RecordingLsp implements LspLifecyclePort { int boots; int shutdowns; From feb57c5298b6af57ad2ec79f847a25d37961bfad Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 08:48:33 +0100 Subject: [PATCH 04/15] package PBS references and expose paginated MCP reads --- ...ent Packaging and Loading Specification.md | 33 ++++ docs/specs/compiler-languages/pbs/README.md | 67 ++++++++ ...CP Tools and Project Knowledge Contract.md | 47 +++++- prometeu-app/build.gradle.kts | 15 +- .../app/StudioApplicationConfiguration.java | 2 +- .../compiler/CompilerProjectKnowledge.java | 72 ++++++++- .../app/mcp/McpProjectKnowledgeTools.java | 12 +- .../main/resources/mcp/studio-tools-v1.json | 5 +- .../StudioApplicationConfigurationTest.java | 3 +- .../CompilerProjectKnowledgeTest.java | 6 +- .../app/compiler/InstalledKnowledgeProbe.java | 62 ++++++++ .../app/compiler/InstalledKnowledgeTest.java | 33 ++++ .../app/compiler/ProjectReferencesTest.java | 143 ++++++++++++++++++ .../p/studio/app/mcp/LocalMcpServerTest.java | 14 ++ .../prometeu-frontend-pbs/build.gradle.kts | 46 ++++++ .../studio/compiler/PBSFrontendProvider.java | 7 + .../pbs/documentation/PbsDocumentation.java | 78 ++++++++++ .../examples/game/1/prometeu.json | 8 + .../examples/game/1/src/main.pbs | 19 +++ .../examples/game/1/src/mod.barrel | 2 + .../documentation/PbsDocumentationTest.java | 60 ++++++++ .../compiler/services/FrontendProvider.java | 4 + .../services/FrontendReferenceProvider.java | 21 +++ 23 files changed, 738 insertions(+), 21 deletions(-) create mode 100644 prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java create mode 100644 prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/compiler/ProjectReferencesTest.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/documentation/PbsDocumentation.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/prometeu.json create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/main.pbs create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/documentation/PbsDocumentationTest.java create mode 100644 prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendReferenceProvider.java diff --git a/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md b/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md index abc9ca91..8c3e02e6 100644 --- a/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md +++ b/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md @@ -323,3 +323,36 @@ The current Studio direction is: 4. the compiler should use explicit abstractions such as `StdlibEnvironment` and `StdlibModuleResolver`, 5. stdlib interface modules are parsed with the normal PBS parser and validated in interface-module mode, 6. reserved attributes such as `[Host(...)]` are extracted as compile-time metadata for later lowering. + +## 13. Installed Language and SDK Reference Bundle + +The PBS frontend distribution MUST provide local, indexed documentation through +the frontend reference-provider contract. This packaging does not create a new +normative specification: the numbered PBS documents in their owner directory +remain authoritative, and the quickstart/example remain informative. + +The build MUST generate the reference index from owner-maintained sources: + +- this directory's numbered specifications and README quickstart; +- the frontend's example manifest, PBS source and barrel; +- the actual packaged SDK `.pbs` and `.barrel` files, including their documentation. + +Generated copies MUST NOT be edited independently. SDK declarations MUST NOT be +rewritten to manufacture a documentation-only API. The index MUST contain stable +reference identities, titles, kinds, packaged-resource identities, content hashes +and applicable SDK major/target. The loader MUST reject missing/corrupted indexed +content instead of advertising unreadable references or consulting a checkout. + +For the current distribution, SDK/example selection is Game / major 1. The general +PBS specifications remain available for other selections, but Game SDK 1 references +MUST NOT be presented as another SDK version or target. An absent SDK reference +set MUST be explicit to consumers. + +Language, compiler, SDK and index-schema versions remain independent. General +specification references use an unknown release version when owner release +metadata is absent; SDK-associated references identify the installed SDK major. +Content hashes identify the packaged texts, not a semantic language release. + +Conformance MUST include reading all indexed references from installed JARs outside +the repository and compiling the shipped example against the installed SDK. No +network access or source checkout may be required by that reference-read path. diff --git a/docs/specs/compiler-languages/pbs/README.md b/docs/specs/compiler-languages/pbs/README.md index d7a43292..dfb149eb 100644 --- a/docs/specs/compiler-languages/pbs/README.md +++ b/docs/specs/compiler-languages/pbs/README.md @@ -2,6 +2,73 @@ This directory contains the normative PBS specification set. +## Installed Quickstart (Informative) + +This guide and the numbered specifications are packaged with the PBS frontend. +They describe the installed distribution, not a promise of a numbered language +release. A spec's `Draft v1` status is not the compiler version or SDK version. +The project manifest selects the SDK major with `stdlib`; current packaged +Game SDK resources use major `1`. Unknown language/compiler versions remain +unknown in Studio's context. + +For an external coding agent: + +1. Request `studio_project_context` for the absolute root of the open project. +2. Read `pbs:quickstart`, `pbs:spec:3` (syntax), `pbs:spec:4` (static semantics) + and the relevant SDK reference IDs returned in that context. Continue pages + until `nextOffset` is null. References are IDs, not filesystem paths. +3. Inspect the project and its dependencies before changing source. Only edit + the project's editable scope, excluding read-only SDK/external libraries. +4. Use the installed LSP and compiler to check changes. When the corresponding + MCP tools are available, acquire project control after the developer's DEV + grant, then use the advertised language/build tools. Documentation reads do + not require that grant. Missing tools/capabilities must not be assumed. +5. Build and test small changes. Runtime execution also requires a compatible + configured runtime; reading references does not install one. + +### Small Game Project + +The installed example has three separately indexed files: + +- `pbs:example:game:1:prometeu.json`: a Game manifest with `language: pbs`, + `stdlib: 1` (serialized as a string), and no external dependencies; +- `pbs:example:game:1:src/main.pbs`: `[Init]` and `[Frame]` functions drawing a + moving rectangle through `Gfx` and constructing colors through `Color`; +- `pbs:example:game:1:src/mod.barrel`: the module's public declarations. + +Copy these reference texts to the corresponding paths only when creating that +example in your editable project. The example is compiled in the test suite; +it is not a complete game or a claim that every requested gameplay abstraction +already exists. If a project has no external dependencies, no registry is needed. +For dependencies, follow the installed compiler's manifest/registry requirements. + +PBS source lives under `src` for the installed provider. Functions use `fn`, +typed parameters and `->` return types. `let` declares a local binding; +`declare global` declares persistent global state. Imports name exports and a +module address, for example `import { Gfx } from @sdk:gfx;`. A `mod.barrel` +describes a module's public surface. Read the syntax/static-semantics chapters +for exact rules rather than inferring compatibility with another language. + +### SDK Navigation and Limits + +`pbs:sdk:game:1:sdk/gfx/main.pbs` exposes the actual installed Gfx source, +including documentation comments and signatures. Its `mod.barrel` reference +defines exports. Equivalent references exist for `sdk/asset`, `sdk/composer`, +`sdk/input`, `sdk/log`, and `core/color`. Read those interfaces before calling +them. Game SDK 1 does not currently ship `audio` or `core/math` modules. + +Ordinary game source uses public services such as `Gfx`; it must not manufacture +host bindings or mutate SDK declarations. Asset/composer workflows require their +real asset/scene data and runtime capabilities. Reference availability does not +guarantee those project resources exist. SDK or tooling limitations should be +reported for separate work, not patched in read-only dependencies. + +The reference index is generated from these owner-maintained documents and the +frontend's SDK/example resources. The index schema revision is not a language +version. Source hashes bind texts to the installed bundle; no repository checkout +or network is needed to read them. The numbered specifications remain normative; +this onboarding section and example are explanatory, not a second specification. + ## Purpose Specs define the official PBS language/frontend contract. 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 01a30573..137b4d8a 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 @@ -184,7 +184,8 @@ Reference reads take an opaque ID from that index, not a path or arbitrary URI. Offset defaults to 0; limit defaults to 4000 and accepts 1–16000 Unicode code points. A page returns referenceId, offset, total, text and nextOffset (null at end). Invalid pagination fails; unknown/traversal-like IDs cannot escape the -index. Installed packaging and real provider resolution are steps 17–18. +index. Installed reference content is resolved through the frontend's owner-maintained +reference provider, not a Studio-maintained language specification. ### 5.1 Manifest and Provider Resolution @@ -230,9 +231,44 @@ symlink targets. SDK entries are always read-only; packaged SDK resources need n have filesystem roots. Scope metadata does not sandbox an external agent's own filesystem tools; the developer remains responsible for those tools and Git. -Paths in MCP results are absolute filesystem strings, not `file:` URIs. Until -step 18 packages the owner-maintained index, references/reference IDs are empty -with `DOCUMENTATION_UNAVAILABLE`; no guessed path or reference is advertised. +Paths in MCP results are absolute filesystem strings, not `file:` URIs. + +### 5.2 Installed References and Pagination + +An installed frontend MAY implement `FrontendReferenceProvider` through +`FrontendProvider.documentation()`. That compiler-side contract supplies indexed, +owner-maintained texts for an SDK major and project target. It does not depend on +Studio API or MCP. Studio projects these into neutral reference descriptors; +full texts MUST NOT be included in project context. Reference IDs are namespaced +by language (`:`), unique within the selected project index and opaque +to callers. Studio MUST NOT interpret an ID as a filename, URI or URL. + +PBS packages its numbered specifications and informative quickstart from their +owner directory, plus a compilable Game example and actual SDK sources/barrels. +A build-generated index binds these texts to the installed frontend using content +hashes. Distribution-only reads MUST work without a checkout or network. SDK and +example references identify their SDK major and target; unsupported selections +MUST NOT silently reuse another SDK/target. Numbered spec/draft revisions and the +reference-index schema revision MUST NOT be reported as language/compiler versions. + +`studio_reference_read` is authenticated but does not require a control grant or +task. It resolves the explicit open root and its current saved manifest selection +on every read. Changing SDK/target can invalidate previously advertised IDs. +Only IDs in that project's installed index can be read, including when other +languages/providers are installed globally. SDK and external-library texts remain +consultable, not editable through this surface. + +Pagination counts Unicode code points: an astral character occupies one offset, +not two UTF-16 units. Offset 0/limit 4000 are defaults; limit MUST be 1–16000. +An offset equal to total returns empty text and null nextOffset. Offsets beyond +total, negative offsets, nonintegral values and integers beyond the implementation's +signed 32-bit range are invalid parameters, never wrapped/truncated to another page. + +Missing or unreadable provider documentation yields `DOCUMENTATION_UNAVAILABLE` +limitations, not promised references. An uninstalled primary language yields +`UNSUPPORTED_LANGUAGE` for reference reads; an available index without the requested +ID yields `REFERENCE_NOT_FOUND`. Closed projects yield `PROJECT_NOT_OPEN` before +reference lookup. These failures do not grant/revoke task authority. ## 6. Image Contract @@ -258,7 +294,8 @@ authentication, Origin, endpoint/method/version handling, tool dispatch, malform 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` as of step 17; other +The production registry composes `studio_project_context` and `studio_reference_read` +as of step 18; other tools are advertised only when their functional handlers are connected. 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 diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 76bb1cf0..6989992f 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -31,7 +31,7 @@ javafx { } // Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. -tasks.named("test") { exclude("**/DevDesktopTest.class") } +tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class") } tasks.register("devDesktopTest") { group = "verification" description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." @@ -41,3 +41,16 @@ tasks.register("devDesktopTest") { include("**/DevDesktopTest.class") systemProperty("java.awt.headless", "false") } + +tasks.register("installedKnowledgeTest") { + group = "verification" + description = "Reads installed references and compiles their example in an isolated JVM outside the checkout." + dependsOn(tasks.named("installDist")) + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/InstalledKnowledgeTest.class") + val distribution = layout.buildDirectory.dir("install/prometeu-app") + inputs.dir(distribution) + systemProperty("studio.test.distribution", distribution.get().asFile.absolutePath) +} 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 cd1c1765..f083c0f7 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -304,7 +304,7 @@ public class StudioApplicationConfiguration { @Bean p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper, p.studio.api.automation.ProjectKnowledge knowledge) { - // Further providers are connected in PLN-0139 steps 18–20. Never advertise placeholders. + // Further providers are connected in PLN-0139 steps 19–20. Never advertise placeholders. return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper)); } diff --git a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java index 36227164..e3fb0e6b 100644 --- a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java +++ b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java @@ -20,6 +20,8 @@ import java.util.*; /** Read-only manifest/provider discovery. Never selects a default frontend or starts a build. */ public final class CompilerProjectKnowledge implements ProjectKnowledge { + private record OwnedReference(String owner, p.studio.compiler.services.FrontendReferenceProvider.Reference reference) {} + private record Discovery(Context context, Map references) {} private static final int MAX_PROJECTS = 256; private final ProjectAccessRegistry openProjects; private final ProjectCatalog projects; @@ -33,6 +35,10 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { } @Override public Context context(Path openProjectRoot) { + return discover(openProjectRoot).context(); + } + + private Discovery discover(Path openProjectRoot) { Path root = openProjects.requireOpenRoot(openProjectRoot); var limitations = new ArrayList(); var discovered = new LinkedHashMap(); @@ -128,12 +134,15 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { } } libraries.addAll(unresolved); + var references = new LinkedHashMap(); + discovered.values().forEach(project -> collectReferences(project, references, limitations)); var languages = new ArrayList(); String primary = discovered.get(root).languageId(); if (byLanguage.size() > 1) limitations.add("The installed build pipeline requires the same language across the dependency graph"); for (var entry : byLanguage.entrySet()) { var language = language(entry.getKey(), entry.getValue(), primary.equals(entry.getKey()), - dependenciesComplete && byLanguage.size() == 1, limitations); + dependenciesComplete && byLanguage.size() == 1, limitations, + references.entrySet().stream().filter(ref -> ref.getValue().owner().equals(entry.getKey())).map(Map.Entry::getKey).toList()); languages.add(language); for (Path source : language.sourceRoots()) if (!source.startsWith(root)) readOnly.add(source); for (var project : entry.getValue()) { @@ -144,15 +153,19 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { } } limitations.add("SDK resources are provider-owned, read-only resources, not editable project files"); - limitations.add("DOCUMENTATION_UNAVAILABLE: installed language/SDK reference index is not yet available"); // Closing a project during discovery must not publish a successful context for that closed project. openProjects.requireOpenRoot(root); - return new Context(root, discovered.get(root).name(), languages, libraries, - List.of(root), List.copyOf(readOnly), List.of(), limitations); + var descriptors = references.values().stream().map(owned -> { + var ref = owned.reference(); + return new Reference(ref.id(), ref.title(), owned.owner(), ReferenceKind.valueOf(ref.kind().name()), + new Version(ref.version(), ref.versionSource())); + }).toList(); + return new Discovery(new Context(root, discovered.get(root).name(), languages, libraries, + List.of(root), List.copyOf(readOnly), descriptors, limitations.stream().distinct().toList()), Map.copyOf(references)); } private Language language(String id, List projects, boolean primary, - boolean graphBuildable, List limitations) { + boolean graphBuildable, List limitations, List referenceIds) { var sdkVersions = projects.stream().map(ProjectReference::stdlibVersion).distinct().toList(); Version sdk = sdkVersions.size() == 1 ? new Version(sdkVersions.getFirst().toString(), "prometeu.json#stdlib (requested)") : Version.unknown(); @@ -161,7 +174,7 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { if (provider.isEmpty()) { limitations.add("UNSUPPORTED_LANGUAGE: no installed frontend for " + id); return new Language(id, primary, Version.unknown(), Version.unknown(), sdk, List.of(), List.of(), - List.of(capability("build", false), capability("lsp", false)), List.of()); + List.of(capability("build", false), capability("lsp", false)), referenceIds); } var spec = provider.get().specification(); var roots = new LinkedHashSet(); @@ -176,7 +189,35 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { String compilerVersion = provider.get().getClass().getPackage().getImplementationVersion(); return new Language(id, primary, Version.unknown(), compilerVersion == null || compilerVersion.isBlank() ? Version.unknown() : new Version(compilerVersion, "installed frontend package Implementation-Version"), sdk, - spec.getAllowedExtensions().stream().sorted().toList(), List.copyOf(roots), capabilities, List.of()); + spec.getAllowedExtensions().stream().sorted().toList(), List.copyOf(roots), capabilities, referenceIds); + } + + private void collectReferences(ProjectReference project, Map references, List limitations) { + String owner = project.languageId(); + String selection = owner + " / " + project.target() + " / SDK " + project.stdlibVersion(); + try { + var documentation = FrontendRegistryService.getProvider(owner).flatMap(p.studio.compiler.services.FrontendProvider::documentation); + if (documentation.isEmpty()) { + limitations.add("DOCUMENTATION_UNAVAILABLE: no installed reference provider for " + owner); + return; + } + var selected = documentation.get().references(project.stdlibVersion(), p.studio.AppMode.valueOf(project.target().name())); + var additions = new LinkedHashMap(); + for (var reference : selected) { + var owned = new OwnedReference(owner, reference); + if (!reference.id().startsWith(owner + ":") + || references.containsKey(reference.id()) && !references.get(reference.id()).equals(owned) + || additions.putIfAbsent(reference.id(), owned) != null) + throw new IllegalStateException("Ambiguous or invalid reference ID"); + } + references.putAll(additions); + if (selected.isEmpty()) limitations.add("DOCUMENTATION_UNAVAILABLE: no installed references for " + selection); + if (selected.stream().noneMatch(ref -> ref.kind() == p.studio.compiler.services.FrontendReferenceProvider.Kind.SDK + && Integer.toString(project.stdlibVersion()).equals(ref.version()))) + limitations.add("DOCUMENTATION_UNAVAILABLE: no installed SDK reference for " + selection); + } catch (RuntimeException unavailable) { + limitations.add("DOCUMENTATION_UNAVAILABLE: cannot load installed references for " + selection); + } } private void addLspCapabilities(String id, ProjectReference project, List capabilities, List limitations) { @@ -224,6 +265,21 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { @Override public ReferencePage readReference(Path openProjectRoot, String referenceId, int offset, int limit) { openProjects.requireOpenRoot(openProjectRoot); - throw new AutomationException(AutomationFailure.Code.DOCUMENTATION_UNAVAILABLE, "No installed reference index is available"); + if (referenceId == null || referenceId.isBlank() || offset < 0 || limit < 1 || limit > 16000) + throw new IllegalArgumentException("Invalid reference ID or pagination"); + var discovery = discover(openProjectRoot); + var reference = discovery.references().get(referenceId); + if (reference == null) { + var primary = discovery.context().languages().stream().filter(Language::primary).findFirst().orElseThrow(); + var code = FrontendRegistryService.getProvider(primary.id()).isEmpty() ? AutomationFailure.Code.UNSUPPORTED_LANGUAGE + : discovery.references().isEmpty() ? AutomationFailure.Code.DOCUMENTATION_UNAVAILABLE : AutomationFailure.Code.REFERENCE_NOT_FOUND; + throw new AutomationException(code, "Reference is not available in this project's installed index"); + } + String text = reference.reference().text(); + int total = text.codePointCount(0, text.length()); + if (offset > total) throw new IllegalArgumentException("Reference offset exceeds its length"); + int next = offset + Math.min(limit, total - offset); + String page = text.substring(text.offsetByCodePoints(0, offset), text.offsetByCodePoints(0, next)); + return new ReferencePage(referenceId, offset, total, next == total ? null : next, page); } } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java index 24ca17d3..114ca1cc 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpProjectKnowledgeTools.java @@ -19,6 +19,16 @@ public final class McpProjectKnowledgeTools { var paths = new SimpleModule().addSerializer(Path.class, new ToStringSerializer()); var wireMapper = mapper.copy().registerModule(paths); return Map.of("studio_project_context", arguments -> McpToolResult.success(mapper, - wireMapper.valueToTree(knowledge.context(Path.of(arguments.path("projectRoot").asText()))))); + wireMapper.valueToTree(knowledge.context(Path.of(arguments.path("projectRoot").asText())))), + "studio_reference_read", arguments -> McpToolResult.success(mapper, wireMapper.valueToTree( + knowledge.readReference(Path.of(arguments.path("projectRoot").asText()), arguments.path("referenceId").asText(), + integer(arguments, "offset", 0), integer(arguments, "limit", 4000))))); + } + + private static int integer(JsonNode arguments, String name, int fallback) { + var value = arguments.get(name); + if (value == null) return fallback; + if (!value.isIntegralNumber() || !value.canConvertToInt()) throw new IllegalArgumentException("Invalid " + name); + return value.intValue(); } } diff --git a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json index 70e8ef26..276b109e 100644 --- a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json +++ b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json @@ -111,6 +111,7 @@ "offset": { "type": "integer", "minimum": 0, + "maximum": 2147483647, "default": 0 }, "limit": { @@ -183,12 +184,12 @@ }, "exampleArguments": { "projectRoot": "/projects/game", - "referenceId": "pbs.quickstart", + "referenceId": "pbs:quickstart", "offset": 0, "limit": 4000 }, "exampleValue": { - "referenceId": "pbs.quickstart", + "referenceId": "pbs:quickstart", "offset": 0, "total": 7, "nextOffset": null, 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 3bfd4033..dc6a5dad 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -30,8 +30,9 @@ 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(1, tools.size()); + org.junit.jupiter.api.Assertions.assertEquals(2, 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()); } assertTrue(executor.isShutdown()); assertFalse(mcp.isRunning()); diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java index f9aeb9f8..d6a26214 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java @@ -45,8 +45,10 @@ class CompilerProjectKnowledgeTest { assertEquals(List.of(root), result.editableRoots()); assertFalse(result.libraries().getFirst().editable()); assertTrue(result.libraries().getFirst().id().startsWith("sdk:pbs:")); - assertTrue(result.references().isEmpty()); - assertTrue(result.limitations().stream().anyMatch(value -> value.contains("DOCUMENTATION_UNAVAILABLE"))); + assertFalse(result.references().isEmpty()); + assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:quickstart"))); + assertTrue(language.referenceIds().contains("pbs:quickstart")); + assertFalse(result.limitations().stream().anyMatch(value -> value.contains("DOCUMENTATION_UNAVAILABLE"))); assertFalse(Files.exists(root.resolve(".workspace"))); assertFalse(Files.exists(root.resolve(".studio"))); } diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java new file mode 100644 index 00000000..2cf02cb5 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java @@ -0,0 +1,62 @@ +package p.studio.app.compiler; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.ProjectKnowledge; +import p.studio.compiler.FrontendRegistryService; +import p.studio.compiler.messages.BuilderPipelineConfig; +import p.studio.compiler.models.BuilderPipelineContext; +import p.studio.compiler.workspaces.BuilderPipelineService; +import p.studio.core.project.*; +import p.studio.utilities.logs.LogAggregator; + +import java.nio.file.Files; +import java.nio.file.Path; + +/** Separate JVM gate: product classes/resources must resolve exclusively from installDist JARs. */ +public final class InstalledKnowledgeProbe { + public static void main(String[] arguments) throws Exception { + var provider = FrontendRegistryService.require("pbs"); + check(provider.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "Frontend must come from installed JAR"); + check(CompilerProjectKnowledge.class.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "App must come from installed JAR"); + check(!Files.exists(Path.of("settings.gradle.kts")) && !Files.exists(Path.of("docs")), "No repository in working directory"); + Path root = Files.createDirectory(Path.of("example")).toRealPath(); + var docs = provider.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()); + } + } + var mapper = new ObjectMapper(); + var access = new ProjectAccessRegistry(); + var registration = access.register(root, () -> { throw new AssertionError("References require no grant"); }, () -> true); + var catalog = new ProjectCatalogService(root, mapper, new ProjectLocalStudioSetupStore(mapper)); + var knowledge = new CompilerProjectKnowledge(access, catalog, mapper); + var context = knowledge.context(root); + for (var kind : java.util.List.of(ProjectKnowledge.ReferenceKind.QUICKSTART, ProjectKnowledge.ReferenceKind.SYNTAX, + ProjectKnowledge.ReferenceKind.SEMANTICS, ProjectKnowledge.ReferenceKind.EXAMPLE, ProjectKnowledge.ReferenceKind.SDK)) + check(context.references().stream().anyMatch(ref -> ref.kind() == kind), "Missing " + kind); + for (var reference : docs) { + var actual = new StringBuilder(); + int offset = 0; + while (true) { + var page = knowledge.readReference(root, reference.id(), offset, 997); + actual.append(page.text()); + if (page.nextOffset() == null) break; + offset = page.nextOffset(); + } + check(actual.toString().equals(reference.text()), "Incorrect installed reference: " + reference.id()); + } + var result = BuilderPipelineService.INSTANCE.compile( + BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), LogAggregator.empty()); + check(result.diagnostics().stream().noneMatch(issue -> issue.isError()), "Example must compile without errors"); + check(result.bytecodeBytes().length > 0, "Example must produce bytecode"); + registration.unsubscribe(); + System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled"); + } + + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java new file mode 100644 index 00000000..9bb71906 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java @@ -0,0 +1,33 @@ +package p.studio.app.compiler; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import static org.junit.jupiter.api.Assertions.*; + +class InstalledKnowledgeTest { + @TempDir Path outsideRepository; + + @Test void installedJarsProvideAllReferencesAndCompileTheExampleOutsideTheCheckout() throws Exception { + Path distribution = Path.of(System.getProperty("studio.test.distribution")); + String jars; + try (var files = Files.list(distribution.resolve("lib"))) { + jars = files.filter(file -> file.toString().endsWith(".jar")).sorted() + .map(Path::toString).collect(Collectors.joining(java.io.File.pathSeparator)); + } + String probeClasses = Path.of(InstalledKnowledgeProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString(); + Path output = outsideRepository.resolve("probe.log"); + var process = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "-cp", jars + java.io.File.pathSeparator + probeClasses, InstalledKnowledgeProbe.class.getName()) + .directory(outsideRepository.toFile()).redirectErrorStream(true).redirectOutput(output.toFile()).start(); + try { + assertTrue(process.waitFor(45, TimeUnit.SECONDS), "Installed knowledge probe timed out"); + String log = Files.readString(output); + assertEquals(0, process.exitValue(), log); + assertTrue(log.contains("references; example compiled"), log); + } finally { if (process.isAlive()) process.destroyForcibly().waitFor(); } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/ProjectReferencesTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/ProjectReferencesTest.java new file mode 100644 index 00000000..c444d5ca --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/compiler/ProjectReferencesTest.java @@ -0,0 +1,143 @@ +package p.studio.app.compiler; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.compiler.FrontendRegistryService; +import p.studio.compiler.models.FrontendSpec; +import p.studio.compiler.services.*; +import p.studio.core.project.*; +import p.studio.utilities.structures.ReadOnlySet; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; + +class ProjectReferencesTest { + @TempDir Path root; + final ObjectMapper mapper = new ObjectMapper(); + final ProjectAccessRegistry access = new ProjectAccessRegistry(); + + CompilerProjectKnowledge knowledge(String language, String sdk) throws Exception { + writeManifest(language, sdk); + access.register(root, () -> { throw new AssertionError("Read needs no grant"); }, () -> true); + return new CompilerProjectKnowledge(access, new ProjectCatalogService(root, mapper, new ProjectLocalStudioSetupStore(mapper)), mapper); + } + + void writeManifest(String language, String sdk) throws Exception { + mapper.writeValue(root.resolve("prometeu.json").toFile(), Map.of("name", "References", "version", "1.0.0", + "language", language, "stdlib", sdk, "target", "Game", "dependencies", List.of())); + } + + @Test void pbsReferenceKindsAndVersionsMatchTheInstalledProviderAndPaginateExactly() throws Exception { + var knowledge = knowledge("pbs", "1"); + var context = knowledge.context(root); + var kinds = context.references().stream().map(ProjectKnowledge.Reference::kind).collect(java.util.stream.Collectors.toSet()); + assertTrue(kinds.containsAll(List.of(ProjectKnowledge.ReferenceKind.QUICKSTART, ProjectKnowledge.ReferenceKind.SYNTAX, + ProjectKnowledge.ReferenceKind.SEMANTICS, ProjectKnowledge.ReferenceKind.EXAMPLE, ProjectKnowledge.ReferenceKind.SDK))); + assertEquals(context.references().size(), context.languages().getFirst().referenceIds().size()); + for (var reference : context.references()) { + assertEquals("pbs", reference.owner()); + if (reference.kind() == ProjectKnowledge.ReferenceKind.SDK || reference.kind() == ProjectKnowledge.ReferenceKind.EXAMPLE) { + assertEquals("1", reference.version().value()); + assertTrue(reference.version().source().contains("SDK")); + } else assertFalse(reference.version().known()); + } + var sdk = "pbs:sdk:game:1:sdk/gfx/main.pbs"; + var expected = FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game) + .stream().filter(ref -> ref.id().equals(sdk)).findFirst().orElseThrow().text(); + var actual = new StringBuilder(); + int offset = 0; + do { + var page = knowledge.readReference(root, sdk, offset, 97); + assertEquals(expected.codePointCount(0, expected.length()), page.total()); + actual.append(page.text()); + if (page.nextOffset() == null) break; + offset = page.nextOffset(); + } while (true); + assertEquals(expected, actual.toString()); + assertTrue(actual.toString().contains("fn fill_rect")); + } + + @Test void unknownAndTraversalLikeIdsNeverReadFilesOrUrls() throws Exception { + var knowledge = knowledge("pbs", "1"); + Path secret = root.resolve("secret.txt"); + Files.writeString(secret, "not a reference"); + for (String id : List.of(secret.toString(), secret.toUri().toString(), "../secret.txt", "pbs:../secret.txt", + "pbs-knowledge/index.json", "pbs:%2e%2e/secret.txt", "https://example.invalid", "pbs:unknown")) { + assertEquals(AutomationFailure.Code.REFERENCE_NOT_FOUND, + assertThrows(AutomationException.class, () -> knowledge.readReference(root, id, 0, 100)).failure().code()); + } + } + + @Test void changedSdkCannotReadPreviouslyAdvertisedSdkOrExampleIds() throws Exception { + var knowledge = knowledge("pbs", "1"); + assertTrue(knowledge.context(root).languages().getFirst().referenceIds().contains("pbs:sdk:game:1:sdk/gfx/main.pbs")); + writeManifest("pbs", "999"); + var context = knowledge.context(root); + assertTrue(context.references().stream().noneMatch(ref -> ref.kind() == ProjectKnowledge.ReferenceKind.SDK || ref.kind() == ProjectKnowledge.ReferenceKind.EXAMPLE)); + assertTrue(context.limitations().stream().anyMatch(value -> value.contains("no installed SDK reference"))); + assertEquals(AutomationFailure.Code.REFERENCE_NOT_FOUND, assertThrows(AutomationException.class, + () -> knowledge.readReference(root, "pbs:sdk:game:1:sdk/gfx/main.pbs", 0, 100)).failure().code()); + assertFalse(knowledge.readReference(root, "pbs:quickstart", 0, 100).text().isEmpty()); + } + + @Test void paginationCountsUnicodeCodePointsAndAcceptsTheExactEnd() throws Exception { + String id = "reference-test"; + register(id, Optional.of((sdk, target) -> List.of(new FrontendReferenceProvider.Reference( + id + ":text", "Unicode text", FrontendReferenceProvider.Kind.QUICKSTART, null, "unknown", "A😀é\nB")))); + try { + var knowledge = knowledge(id, "1"); + var emoji = knowledge.readReference(root, id + ":text", 1, 1); + assertEquals("😀", emoji.text()); + assertEquals(5, emoji.total()); + assertEquals(2, emoji.nextOffset()); + var end = knowledge.readReference(root, id + ":text", 5, 100); + assertEquals("", end.text()); assertNull(end.nextOffset()); + for (int offset : List.of(-1, 6, Integer.MAX_VALUE)) + assertThrows(IllegalArgumentException.class, () -> knowledge.readReference(root, id + ":text", offset, 1)); + for (int limit : List.of(0, -1, 16001)) + assertThrows(IllegalArgumentException.class, () -> knowledge.readReference(root, id + ":text", 0, limit)); + } finally { FrontendRegistryService.unregister(id); } + } + + @Test void missingDocumentationAndUnsupportedLanguageHaveExplicitFailures() throws Exception { + String id = "reference-test"; + register(id, Optional.empty()); + try { + var knowledge = knowledge(id, "1"); + assertTrue(knowledge.context(root).references().isEmpty()); + assertEquals(AutomationFailure.Code.DOCUMENTATION_UNAVAILABLE, assertThrows(AutomationException.class, + () -> knowledge.readReference(root, id + ":text", 0, 100)).failure().code()); + writeManifest("uninstalled", "1"); + assertEquals(AutomationFailure.Code.UNSUPPORTED_LANGUAGE, assertThrows(AutomationException.class, + () -> knowledge.readReference(root, id + ":text", 0, 100)).failure().code()); + } finally { FrontendRegistryService.unregister(id); } + } + + @Test void failingProviderDoesNotAdvertiseUnreadableReferences() throws Exception { + String id = "reference-test"; + register(id, Optional.of((sdk, target) -> { throw new IllegalStateException("Missing installed index"); })); + try { + var knowledge = knowledge(id, "1"); + var context = knowledge.context(root); + assertTrue(context.references().isEmpty()); + assertTrue(context.limitations().stream().anyMatch(value -> value.contains("cannot load installed references"))); + assertEquals(AutomationFailure.Code.DOCUMENTATION_UNAVAILABLE, assertThrows(AutomationException.class, + () -> knowledge.readReference(root, id + ":text", 0, 100)).failure().code()); + } finally { FrontendRegistryService.unregister(id); } + } + + private void register(String id, Optional documentation) { + FrontendRegistryService.register(new FrontendProvider() { + @Override public FrontendSpec specification() { + return FrontendSpec.builder().languageId(id).allowedExtensions(ReadOnlySet.from("alt")) + .sourceRoots(ReadOnlySet.from("src")).stdlibVersions(List.of(FrontendSpec.Stdlib.of(1))).build(); + } + @Override public FrontendPhaseService compiler() { throw new AssertionError("No compilation for reference reads"); } + @Override public Optional documentation() { return documentation; } + }); + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java index 6db162f0..037a57fc 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java @@ -129,6 +129,20 @@ class LocalMcpServerTest { assertEquals("pbs", value.path("languages").get(0).path("id").asText()); assertTrue(value.path("languages").get(0).path("languageVersion").path("value").isNull()); assertFalse(java.nio.file.Files.exists(root.resolve(".studio"))); + var params = (com.fasterxml.jackson.databind.node.ObjectNode) call.path("params"); + params.put("name", "studio_reference_read"); + var arguments = (com.fasterxml.jackson.databind.node.ObjectNode) params.path("arguments"); + arguments.put("referenceId", "pbs:quickstart"); + var page = mapper.readTree(post(call.toString()).body()).path("result").path("structuredContent").path("value"); + assertEquals(0, page.path("offset").asInt()); + assertEquals(4000, page.path("text").asText().codePointCount(0, page.path("text").asText().length())); + assertEquals(4000, page.path("nextOffset").asInt()); + arguments.put("offset", 4294967296L); + assertEquals(-32602, mapper.readTree(post(call.toString()).body()).path("error").path("code").asInt()); + arguments.remove("offset"); + arguments.put("referenceId", "../../prometeu.json"); + var missing = mapper.readTree(post(call.toString()).body()).path("result"); + assertEquals("REFERENCE_NOT_FOUND", missing.path("structuredContent").path("error").path("code").asText()); registration.unsubscribe(); var denied = mapper.readTree(post(call.toString()).body()).path("result"); assertTrue(denied.path("isError").asBoolean()); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/build.gradle.kts b/prometeu-compiler/frontends/prometeu-frontend-pbs/build.gradle.kts index f2820da2..a7adba65 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/build.gradle.kts +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/build.gradle.kts @@ -1,3 +1,5 @@ +import java.security.MessageDigest + plugins { id("gradle.java-library-conventions") } @@ -8,3 +10,47 @@ dependencies { implementation(project(":prometeu-compiler:prometeu-frontend-api")) implementation(project(":prometeu-compiler:prometeu-compiler-core")) } + +// Build-time projection of owner-maintained sources; no second normative copy is edited by Studio. +val pbsSpecs = rootProject.layout.projectDirectory.dir("docs/specs/compiler-languages/pbs") +val pbsResources = layout.projectDirectory.dir("src/main/resources") +val generatePbsKnowledge by tasks.registering(Sync::class) { + from(pbsSpecs) { include("*.md"); into("pbs-knowledge/specs") } + into(layout.buildDirectory.dir("generated/pbsKnowledge")) + inputs.files(fileTree(pbsResources) { include("game/stdlib/**/*.pbs", "game/stdlib/**/*.barrel", "pbs-knowledge/examples/**") }) + doLast { + val entries = mutableListOf>() + fun entry(id: String, title: String, kind: String, resource: String, source: File, sdk: Int? = null, target: String? = null) { + check(source.isFile) { "Missing PBS reference: $source" } + val digest = MessageDigest.getInstance("SHA-256").digest(source.readBytes()) + .joinToString("") { "%02x".format(it) } + entries.add(linkedMapOf("id" to id, "title" to title, "kind" to kind, + "resource" to resource, "sha256" to digest, "sdkVersion" to sdk, "target" to target)) + } + pbsSpecs.asFile.listFiles()!!.filter { it.extension == "md" }.sortedBy { it.name }.forEach { source -> + val chapter = source.name.substringBefore(". ") + val quickstart = source.name == "README.md" + entry(if (quickstart) "pbs:quickstart" else "pbs:spec:$chapter", + source.readLines().first { it.startsWith("# ") }.removePrefix("# "), + if (quickstart) "QUICKSTART" else if (chapter == "3") "SYNTAX" else "SEMANTICS", + "pbs-knowledge/specs/${source.name}", source) + } + fileTree(pbsResources) { include("game/stdlib/**/*.pbs", "game/stdlib/**/*.barrel") }.files.sorted().forEach { source -> + val path = source.relativeTo(pbsResources.asFile).invariantSeparatorsPath + val parts = path.split('/') + val sdk = parts[2].toInt() + val module = parts.drop(3).dropLast(1).joinToString(":") + entry("pbs:sdk:game:$sdk:${parts.drop(3).joinToString("/")}", "PBS SDK $sdk @$module / ${source.name}", + "SDK", path, source, sdk, "Game") + } + fileTree(pbsResources.dir("pbs-knowledge/examples/game/1")) { include("**/*") }.files.sorted().forEach { source -> + val relative = source.relativeTo(pbsResources.dir("pbs-knowledge/examples/game/1").asFile).invariantSeparatorsPath + entry("pbs:example:game:1:$relative", "PBS Game / SDK 1 example: $relative", "EXAMPLE", + "pbs-knowledge/examples/game/1/$relative", source, 1, "Game") + } + check(entries.map { it["id"] }.distinct().size == entries.size) { "Duplicate PBS reference IDs" } + destinationDir.resolve("pbs-knowledge/index.json").writeText(groovy.json.JsonOutput.prettyPrint( + groovy.json.JsonOutput.toJson(mapOf("schemaVersion" to 1, "owner" to "pbs", "references" to entries)))) + } +} +sourceSets.main { resources.srcDir(generatePbsKnowledge) } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendProvider.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendProvider.java index a411072a..076e8075 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendProvider.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendProvider.java @@ -11,6 +11,8 @@ import java.util.Optional; public final class PBSFrontendProvider implements FrontendProvider { private final FrontendPhaseService compiler; private final PBSFrontendLanguageService languageService; + private final p.studio.compiler.services.FrontendReferenceProvider documentation = + new p.studio.compiler.pbs.documentation.PbsDocumentation(); public PBSFrontendProvider() { this(new PBSFrontendPhaseService(), new PBSFrontendLanguageService()); @@ -41,4 +43,9 @@ public final class PBSFrontendProvider implements FrontendProvider { public Optional languageService() { return Optional.of(languageService); } + + @Override + public Optional documentation() { + return Optional.of(documentation); + } } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/documentation/PbsDocumentation.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/documentation/PbsDocumentation.java new file mode 100644 index 00000000..cb0b269e --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/documentation/PbsDocumentation.java @@ -0,0 +1,78 @@ +package p.studio.compiler.pbs.documentation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.AppMode; +import p.studio.compiler.services.FrontendReferenceProvider; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.*; +import java.io.InputStream; +import java.util.function.Function; + +/** Loads only the build-generated PBS index and its packaged resources, never user-supplied paths. */ +public final class PbsDocumentation implements FrontendReferenceProvider { + private record Index(int schemaVersion, String owner, List references) {} + private record Entry(String id, String title, Kind kind, String resource, String sha256, + Integer sdkVersion, String target) {} + private record Installed(Entry entry, Reference reference) {} + private final Function resources; + private volatile List installed; + + public PbsDocumentation() { this(PbsDocumentation.class.getClassLoader()::getResourceAsStream); } + PbsDocumentation(Function resources) { this.resources = Objects.requireNonNull(resources); } + + @Override public List references(int stdlibVersion, AppMode target) { + Objects.requireNonNull(target); + return installed().stream() + .filter(item -> item.entry().sdkVersion() == null || item.entry().sdkVersion() == stdlibVersion) + .filter(item -> item.entry().target() == null || item.entry().target().equals(target.name())) + .map(Installed::reference).toList(); + } + + private List installed() { + if (installed != null) return installed; + synchronized (this) { + if (installed != null) return installed; + try { + var index = new ObjectMapper().readValue(resource("pbs-knowledge/index.json"), Index.class); + if (index.schemaVersion() != 1 || !"pbs".equals(index.owner()) || index.references() == null) + throw new IOException("Invalid PBS reference index"); + var entries = new ArrayList(); + var ids = new HashSet(); + for (var entry : index.references()) { + if (entry.id() == null || !entry.id().startsWith("pbs:") || !ids.add(entry.id()) + || entry.sdkVersion() != null && entry.sdkVersion() < 1) + throw new IOException("Invalid or duplicate PBS reference identity"); + byte[] bytes = resource(entry.resource()); + if (!HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)).equals(entry.sha256())) + throw new IOException("PBS reference does not match its installed index"); + String content = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString(); + entries.add(new Installed(entry, new Reference(entry.id(), entry.title(), entry.kind(), + entry.sdkVersion() == null ? null : entry.sdkVersion().toString(), + entry.sdkVersion() == null ? "unknown" : "installed PBS SDK major; target=" + entry.target(), content))); + } + installed = List.copyOf(entries); + return installed; + } catch (Exception failure) { + throw new IllegalStateException("Installed PBS documentation is unavailable", failure); + } + } + } + + private byte[] resource(String path) throws IOException { + if (path == null || path.contains("..") || path.contains(":") || path.contains("\\") + || !(path.startsWith("pbs-knowledge/") || path.startsWith("game/stdlib/"))) + throw new IOException("Invalid PBS reference resource"); + try (var stream = resources.apply(path)) { + if (stream == null) throw new IOException("Missing PBS reference resource"); + byte[] bytes = stream.readNBytes(4 * 1024 * 1024 + 1); + if (bytes.length > 4 * 1024 * 1024) throw new IOException("PBS reference resource is too large"); + return bytes; + } + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/prometeu.json b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/prometeu.json new file mode 100644 index 00000000..0f45469a --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/prometeu.json @@ -0,0 +1,8 @@ +{ + "name": "pbs-reference-example", + "version": "1.0.0", + "language": "pbs", + "stdlib": "1", + "target": "Game", + "dependencies": [] +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/main.pbs new file mode 100644 index 00000000..e2f6e8f2 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/main.pbs @@ -0,0 +1,19 @@ +import { Color } from @core:color; +import { Gfx } from @sdk:gfx; + +declare global x: int = 0; + +[Init] +fn init() -> void { + x = 0; +} + +[Frame] +fn frame() -> void { + Gfx.clear(Color.rgb(16, 20, 28)); + Gfx.fill_rect(x, 32, 16, 16, Color.rgb(240, 160, 48)); + x = x + 1; + if (x > 120) { + x = 0; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel new file mode 100644 index 00000000..7c7443f6 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel @@ -0,0 +1,2 @@ +pub fn init() -> void; +pub fn frame() -> void; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/documentation/PbsDocumentationTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/documentation/PbsDocumentationTest.java new file mode 100644 index 00000000..0039026e --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/documentation/PbsDocumentationTest.java @@ -0,0 +1,60 @@ +package p.studio.compiler.pbs.documentation; + +import org.junit.jupiter.api.Test; +import p.studio.AppMode; +import p.studio.compiler.services.FrontendReferenceProvider; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; + +class PbsDocumentationTest { + @Test void installedIndexHasAllKindsUniqueIdsAndExactSdkSources() throws Exception { + var references = new PbsDocumentation().references(1, AppMode.Game); + assertEquals(references.size(), references.stream().map(FrontendReferenceProvider.Reference::id).distinct().count()); + for (var kind : List.of(FrontendReferenceProvider.Kind.QUICKSTART, FrontendReferenceProvider.Kind.SYNTAX, + FrontendReferenceProvider.Kind.SEMANTICS, FrontendReferenceProvider.Kind.EXAMPLE, FrontendReferenceProvider.Kind.SDK)) + assertTrue(references.stream().anyMatch(ref -> ref.kind() == kind)); + for (var reference : references) { + assertFalse(reference.text().isBlank()); + if (reference.kind() != FrontendReferenceProvider.Kind.SDK) continue; + try (var stream = getClass().getClassLoader().getResourceAsStream("game/stdlib/1/" + reference.id().substring("pbs:sdk:game:1:".length()))) { + assertNotNull(stream); + assertEquals(new String(stream.readAllBytes(), StandardCharsets.UTF_8), reference.text()); + assertEquals("1", reference.version()); + } + } + } + + @Test void unsupportedSdkOrTargetDoesNotBorrowAnotherSdkOrExample() { + var docs = new PbsDocumentation(); + for (var selection : List.of(docs.references(999, AppMode.Game), docs.references(1, AppMode.Shell))) { + assertFalse(selection.isEmpty()); + assertTrue(selection.stream().noneMatch(ref -> ref.kind() == FrontendReferenceProvider.Kind.SDK || ref.kind() == FrontendReferenceProvider.Kind.EXAMPLE)); + assertTrue(selection.stream().allMatch(ref -> ref.version() == null && ref.versionSource().equals("unknown"))); + } + } + + @Test void missingIndexAndCorruptedContentFailExplicitly() { + assertThrows(IllegalStateException.class, () -> new PbsDocumentation(path -> null).references(1, AppMode.Game)); + var corrupt = new PbsDocumentation(path -> path.equals("pbs-knowledge/index.json") + ? getClass().getClassLoader().getResourceAsStream(path) + : new ByteArrayInputStream("corrupted resource".getBytes(StandardCharsets.UTF_8))); + assertThrows(IllegalStateException.class, () -> corrupt.references(1, AppMode.Game)); + } + + @Test void invalidIndexResourceCannotReachTheResourceLoader() { + var opened = new ArrayList(); + String invalidIndex = """ + {"schemaVersion":1,"owner":"pbs","references":[ + {"id":"pbs:bad","title":"Bad","kind":"SYNTAX","resource":"../private.txt","sha256":"invalid"} + ]} + """; + var docs = new PbsDocumentation(path -> { + opened.add(path); + return new ByteArrayInputStream(invalidIndex.getBytes(StandardCharsets.UTF_8)); + }); + assertThrows(IllegalStateException.class, () -> docs.references(1, AppMode.Game)); + assertEquals(List.of("pbs-knowledge/index.json"), opened); + } +} diff --git a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java index 339c96be..a1b616d1 100644 --- a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java +++ b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java @@ -12,4 +12,8 @@ public interface FrontendProvider { default Optional languageService() { return Optional.empty(); } + + default Optional documentation() { + return Optional.empty(); + } } diff --git a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendReferenceProvider.java b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendReferenceProvider.java new file mode 100644 index 00000000..60a7c58c --- /dev/null +++ b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendReferenceProvider.java @@ -0,0 +1,21 @@ +package p.studio.compiler.services; + +import p.studio.AppMode; +import java.util.List; +import java.util.Objects; + +/** Owner-maintained, installed reference texts. This is not a filesystem or network reader. */ +public interface FrontendReferenceProvider { + List references(int stdlibVersion, AppMode target); + + enum Kind { QUICKSTART, SYNTAX, SEMANTICS, EXAMPLE, SDK, LIBRARY } + + record Reference(String id, String title, Kind kind, String version, String versionSource, String text) { + public Reference { + Objects.requireNonNull(id); Objects.requireNonNull(title); Objects.requireNonNull(kind); + Objects.requireNonNull(versionSource); Objects.requireNonNull(text); + if (id.isBlank() || title.isBlank() || versionSource.isBlank() || version != null && version.isBlank()) + throw new IllegalArgumentException("Blank reference metadata"); + } + } +} From c1834bad1f68fc4a4236d2770f4ce977d5270ef4 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 09:21:59 +0100 Subject: [PATCH 05/15] connect MCP language queries to project LSP --- ...CP Tools and Project Knowledge Contract.md | 66 ++++- prometeu-app/build.gradle.kts | 1 + .../app/StudioApplicationConfiguration.java | 21 +- .../compiler/CompilerProjectKnowledge.java | 2 + .../studio/app/lsp/AutomationLspQueries.java | 245 ++++++++++++++++++ .../p/studio/app/lsp/LspLifecycleAdapter.java | 18 +- .../p/studio/app/mcp/McpLanguageTools.java | 18 ++ .../main/resources/mcp/studio-tools-v1.json | 2 +- .../StudioApplicationConfigurationTest.java | 3 +- .../app/lsp/AutomationLspQueriesTest.java | 210 +++++++++++++++ .../architecture/StudioBoundaryArchTest.java | 2 +- .../p/studio/lsp/api/LspServerLifecycle.java | 4 + .../lsp/services/LspServerLifecycleImpl.java | 6 + .../studio/lsp/services/TcpLspServerHost.java | 18 +- .../lsp/services/LspServerLifecycleTest.java | 37 +++ .../api/automation/AutomationSession.java | 2 + .../api/automation/LanguageQueries.java | 9 + .../core/language/LanguageQueryPort.java | 10 + .../core/language/TaskLanguageQueries.java | 55 ++++ .../core/project/ProjectAccessRegistry.java | 19 +- .../session/DefaultAutomationSession.java | 9 + .../session/DefaultProjectSessionFactory.java | 2 +- .../p/studio/core/StudioModularityTest.java | 2 +- .../session/DefaultAutomationSessionTest.java | 17 ++ 24 files changed, 757 insertions(+), 21 deletions(-) create mode 100644 prometeu-app/src/main/java/p/studio/app/lsp/AutomationLspQueries.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpLanguageTools.java create mode 100644 prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java create mode 100644 prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/LanguageQueries.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/language/LanguageQueryPort.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java 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 137b4d8a..4a5c5e9b 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 @@ -125,6 +125,68 @@ symbols reuse the existing project LSP. Other queries/refactoring proposals are exposed only when supported; returned edits MUST respect project versus read-only SDK/library scope. No query applies filesystem edits. +### 3.1 Language Query Operations + +`studio_language_query` uses the existing project's LSP server via a real client, +not a parallel language implementation or a direct call into compiler semantics. +Its successful value is `{operation, result, limitations}`. `result` is the JSON +projection of the existing LSP response (including null or an empty list when +appropriate); LSP union wrappers are unwrapped. Provider classes remain inside +the application adapter. Studio API/Core use maps, lists and scalar values only. + +| Operation | Required parameters beyond projectRoot/taskId | +| --- | --- | +| `diagnostics`, `documentSymbols`, `documentLinks`, `foldingRanges`, `formatting`, `semanticTokens` | `parameters.uri` | +| `hover`, `completion`, `signatureHelp`, `definition`, `references`, `prepareRename`, `prepareCallHierarchy` | `uri`, `position`; references optionally accepts `includeDeclaration` | +| `rename` | `uri`, `position`, `newName` | +| `workspaceSymbols` | optional `query`; no document URI is needed | +| `selectionRanges` | `uri`, nonempty `positions` | +| `codeActions` | `uri`, ordered `range`; diagnostics are obtained from the current saved file | +| `incomingCalls`, `outgoingCalls` | task-local `itemId` from a hierarchy result | + +Support MUST be checked against the running server's initialize response before +dispatch. Unknown operations, including currently unsupported type hierarchy, +return `UNSUPPORTED_CAPABILITY`. Context publishes the installed provider's +capabilities, including semantic tokens; hierarchy and rename preparations use +their corresponding server capability. Positions are zero-based UTF-16 offsets, +must fit the saved file and must not split surrogate pairs. Reversed ranges and +missing operation-specific parameters are rejected. + +The application lifecycle supplies each open project's bound loopback LSP +endpoint. Studio uses OS-assigned ports so different open projects do not compete +for one fixed port. The public LSP configuration default remains unchanged for +other hosts. A manifest language change requires reopening that project's server; +the adapter MUST NOT send queries to a server bound to another language/root. + +Each query uses a short-lived client connection. For document requests, the +adapter opens exactly the saved UTF-8 text and waits for that connection's +published diagnostics before issuing the semantic query. Other dependency files +are read from disk by the existing compiler bridge. A fresh connection prevents +reuse of stale overlays from previous requests or the human editor. Unsaved or +concurrent external writes remain the developer's responsibility. + +Queries require the current task, share the project's work admission/cancellation +and DEV operation observation, and do not silently queue behind conflicting work. +Return/reclaim invalidates the task immediately, waits for worker termination, +then clears task-local hierarchy items before manual control is restored. Item +IDs from another task or project cannot be used. Client sockets/listeners close +on success, failure, timeout or cancellation; project-server shutdown closes its +accepted sockets and executor. A lost client does not independently grant control. + +The adapter bounds connect time to 2 seconds and the LSP exchange to 10 seconds; +Core bounds the request worker wait to 12 seconds. Documents are limited to 4 MiB +of UTF-8 and task-local hierarchy state to 1024 items. These are adapter resource +guards, unrelated to the runtime's deterministic frame/watchdog semantics. + +Document URIs must resolve to known physical project/dependency source files. +Symlink targets are canonicalized before admission. External sources may be +queried, but edit-producing queries on read-only roots are rejected. Every URI in +returned workspace-edit proposals is checked against the same editable/read-only +scope; an unsafe proposal is rejected as a whole. File-operation edits and +executable commands are not offered; `workspace/applyEdit` is always refused. +No query writes a file. Virtual SDK declarations may not have physical definition +locations in the existing LSP; indexed SDK references remain available instead. + ## 4. Result, Error and Operation Contracts Successful tools return `isError:false` with structuredContent @@ -294,8 +356,8 @@ authentication, Origin, endpoint/method/version handling, tool dispatch, malform 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` and `studio_reference_read` -as of step 18; other +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. 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 diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 6989992f..1e2ad67e 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -17,6 +17,7 @@ dependencies { implementation(project(":prometeu-studio-core")) implementation(project(":prometeu-studio-ui-javafx")) implementation(libs.spring.boot) + implementation(libs.lsp4j) implementation(libs.javafx.controls) implementation(libs.javafx.fxml) } 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 f083c0f7..f19dbae9 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -301,12 +301,25 @@ public class StudioApplicationConfiguration { return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper); } + @Bean + p.studio.core.language.LanguageQueryPort automationLanguagePort(LspServerLifecycle lifecycle, ProjectCatalog catalog, + p.studio.api.automation.ProjectKnowledge knowledge, ObjectMapper mapper) { + return new p.studio.app.lsp.AutomationLspQueries(lifecycle, catalog, knowledge, mapper); + } + + @Bean + p.studio.api.automation.LanguageQueries languageQueries(p.studio.core.project.ProjectAccessRegistry projects, + p.studio.core.language.LanguageQueryPort language) { + return new p.studio.core.language.TaskLanguageQueries(projects, language); + } + @Bean p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper, - p.studio.api.automation.ProjectKnowledge knowledge) { - // Further providers are connected in PLN-0139 steps 19–20. Never advertise placeholders. - return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, - p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, 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. + var handlers = new java.util.LinkedHashMap<>(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper)); + handlers.putAll(p.studio.app.mcp.McpLanguageTools.handlers(language, mapper)); + return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers); } @Bean(initMethod = "start", destroyMethod = "close") diff --git a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java index e3fb0e6b..f5013a0a 100644 --- a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java +++ b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java @@ -153,6 +153,7 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { } } limitations.add("SDK resources are provider-owned, read-only resources, not editable project files"); + limitations.add("Virtual SDK symbols may have no physical LSP definition location; consult indexed SDK references"); // Closing a project during discovery must not publish a successful context for that closed project. openProjects.requireOpenRoot(root); var descriptors = references.values().stream().map(owned -> { @@ -232,6 +233,7 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { } capabilities.add(capability("lsp", true)); capabilities.add(capability("diagnostics", true)); + capabilities.add(capability("semanticTokens", true)); capabilities.add(capability("hover", server.hoverSupported())); capabilities.add(capability("completion", server.completionSupported())); capabilities.add(capability("signatureHelp", server.signatureHelpSupported())); diff --git a/prometeu-app/src/main/java/p/studio/app/lsp/AutomationLspQueries.java b/prometeu-app/src/main/java/p/studio/app/lsp/AutomationLspQueries.java new file mode 100644 index 00000000..a6da7ee9 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/lsp/AutomationLspQueries.java @@ -0,0 +1,245 @@ +package p.studio.app.lsp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.eclipse.lsp4j.*; +import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.lsp4j.launch.LSPLauncher; +import org.eclipse.lsp4j.services.*; +import p.studio.api.automation.*; +import p.studio.api.project.ProjectCatalog; +import p.studio.core.language.LanguageQueryPort; +import p.studio.lsp.api.LspServerLifecycle; + +import java.net.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; + +/** A real client of the already-running project LSP. Each query owns and closes its connection. */ +public final class AutomationLspQueries implements LanguageQueryPort { + private final LspServerLifecycle lifecycle; + private final ProjectCatalog projects; + private final ProjectKnowledge knowledge; + private final ObjectMapper mapper; + private final com.google.gson.Gson gson = new MessageJsonHandler(Map.of()).getGson(); + private final Map> items = new ConcurrentHashMap<>(); + private static final Set OPERATIONS = Set.of("diagnostics", "completion", "hover", "signatureHelp", "definition", + "references", "documentSymbols", "workspaceSymbols", "prepareRename", "rename", "codeActions", "formatting", + "documentLinks", "foldingRanges", "selectionRanges", "prepareCallHierarchy", "incomingCalls", "outgoingCalls", "semanticTokens"); + private static final Set EDITS = Set.of("completion", "prepareRename", "rename", "codeActions", "formatting"); + + public AutomationLspQueries(LspServerLifecycle lifecycle, ProjectCatalog projects, ProjectKnowledge knowledge, ObjectMapper mapper) { + this.lifecycle = lifecycle; this.projects = projects; this.knowledge = knowledge; this.mapper = mapper; + } + + @Override public void endTask(TaskIdentity task) { items.remove(task); } + + @Override public Map query(TaskIdentity task, String operation, Map parameters) throws Exception { + if (!OPERATIONS.contains(operation)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "Unsupported language operation: " + operation); + var context = knowledge.context(task.projectRoot()); + var primary = context.languages().stream().filter(ProjectKnowledge.Language::primary).findFirst().orElseThrow(); + if (primary.capabilities().stream().anyMatch(cap -> cap.name().equals("lsp") && cap.support() != ProjectKnowledge.Support.SUPPORTED)) + throw failure(AutomationFailure.Code.UNSUPPORTED_LANGUAGE, "Project language has no available LSP"); + var project = projects.openProject(context.projectRoot()); + var binding = LspLifecycleAdapter.context(project); + var endpoint = lifecycle.endpoint(binding).orElseThrow(() -> failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Project LSP is not running; reopen the project if its language changed")); + var params = mapper.valueToTree(parameters); + CallHierarchyItem item = null; + String uri = null; + if (operation.equals("incomingCalls") || operation.equals("outgoingCalls")) { + item = items.getOrDefault(task, Map.of()).get(params.path("itemId").asText()); + if (item == null) throw new IllegalArgumentException("Unknown task-local hierarchy itemId"); + uri = item.getUri(); + } else if (!operation.equals("workspaceSymbols")) { + uri = params.path("uri").asText(null); + if (uri == null) throw new IllegalArgumentException("uri is required"); + } + Path document = uri == null ? null : sourcePath(context, uri); + if (document != null && EDITS.contains(operation)) requireEditable(context, document.toUri().toString()); + String source = null; + if (document != null) { + try (var input = Files.newInputStream(document)) { + var bytes = input.readNBytes(4 * 1024 * 1024 + 1); + if (bytes.length > 4 * 1024 * 1024) throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Source document exceeds 4 MiB"); + source = java.nio.charset.StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + } + uri = document.toUri().toString(); + } + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + var workers = Executors.newCachedThreadPool(r -> { var thread = new Thread(r, "studio-automation-lsp"); thread.setDaemon(true); return thread; }); + try (var socket = new Socket()) { + if (!InetAddress.getByName(endpoint.host()).isLoopbackAddress()) throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Project LSP endpoint is not local"); + socket.connect(new InetSocketAddress(endpoint.host(), endpoint.port()), 2000); + var diagnostics = new CompletableFuture>(); + String expectedUri = uri; + LanguageClient client = new LanguageClient() { + public void telemetryEvent(Object event) {} + public void publishDiagnostics(PublishDiagnosticsParams event) { if (Objects.equals(event.getUri(), expectedUri)) diagnostics.complete(List.copyOf(event.getDiagnostics())); } + public void showMessage(MessageParams message) {} + public CompletableFuture showMessageRequest(ShowMessageRequestParams request) { return CompletableFuture.completedFuture(null); } + public void logMessage(MessageParams message) {} + @Override public CompletableFuture applyEdit(ApplyWorkspaceEditParams edit) { + return CompletableFuture.completedFuture(new ApplyWorkspaceEditResponse(false)); + } + }; + var launcher = LSPLauncher.createClientLauncher(client, socket.getInputStream(), socket.getOutputStream(), workers, consumer -> consumer); + var listening = launcher.startListening(); + try { + var server = launcher.getRemoteProxy(); + var initialize = new InitializeParams(); + initialize.setRootUri(binding.projectRoot().toUri().toString()); + initialize.setCapabilities(new ClientCapabilities()); + var capabilities = await(server.initialize(initialize), deadline).getCapabilities(); + server.initialized(new InitializedParams()); + requireCapability(operation, capabilities); + List currentDiagnostics = List.of(); + if (document != null) { + // Fresh client overlay contains exactly the saved UTF-8 file. Wait for analysis before querying. + server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, primary.id(), 1, source))); + currentDiagnostics = await(diagnostics, deadline); + } + var text = server.getTextDocumentService(); + var id = uri == null ? null : new TextDocumentIdentifier(uri); + Object result = switch (operation) { + case "diagnostics" -> currentDiagnostics; + case "hover" -> await(text.hover(new HoverParams(id, position(params.path("position"), source))), deadline); + case "completion" -> await(text.completion(new CompletionParams(id, position(params.path("position"), source))), deadline); + case "signatureHelp" -> await(text.signatureHelp(new SignatureHelpParams(id, position(params.path("position"), source))), deadline); + case "definition" -> await(text.definition(new DefinitionParams(id, position(params.path("position"), source))), deadline); + case "references" -> await(text.references(new ReferenceParams(id, position(params.path("position"), source), new ReferenceContext(params.path("includeDeclaration").asBoolean(false)))), deadline); + case "documentSymbols" -> await(text.documentSymbol(new DocumentSymbolParams(id)), deadline); + case "workspaceSymbols" -> await(server.getWorkspaceService().symbol(new WorkspaceSymbolParams(params.path("query").asText(""))), deadline); + case "prepareRename" -> await(text.prepareRename(new PrepareRenameParams(id, position(params.path("position"), source))), deadline); + case "rename" -> { + String name = params.path("newName").asText(""); + if (name.isBlank()) throw new IllegalArgumentException("newName is required"); + yield await(text.rename(new RenameParams(id, position(params.path("position"), source), name)), deadline); + } + case "formatting" -> await(text.formatting(new DocumentFormattingParams(id, new FormattingOptions(4, true))), deadline); + case "codeActions" -> await(text.codeAction(new CodeActionParams(id, + range(params.path("range"), source), + new CodeActionContext(currentDiagnostics))), deadline); + case "documentLinks" -> await(text.documentLink(new DocumentLinkParams(id)), deadline); + case "foldingRanges" -> await(text.foldingRange(new FoldingRangeRequestParams(id)), deadline); + case "selectionRanges" -> { + if (!params.path("positions").isArray() || params.path("positions").isEmpty()) throw new IllegalArgumentException("positions are required"); + var positions = new ArrayList(); + for (var p : params.path("positions")) positions.add(position(p, source)); + yield await(text.selectionRange(new SelectionRangeParams(id, positions)), deadline); + } + case "prepareCallHierarchy" -> await(text.prepareCallHierarchy(new CallHierarchyPrepareParams(id, position(params.path("position"), source))), deadline); + case "incomingCalls" -> await(text.callHierarchyIncomingCalls(new CallHierarchyIncomingCallsParams(item)), deadline); + case "outgoingCalls" -> await(text.callHierarchyOutgoingCalls(new CallHierarchyOutgoingCallsParams(item)), deadline); + case "semanticTokens" -> await(text.semanticTokensFull(new SemanticTokensParams(id)), deadline); + default -> throw new IllegalArgumentException("Unsupported operation"); + }; + var wire = mapper.readTree(gson.toJson(result)); + validateEdits(context, wire); + var limitations = new ArrayList(); + if (operation.equals("codeActions") && wire.isArray()) { + for (var action : wire) if (action.has("command")) { + ((com.fasterxml.jackson.databind.node.ObjectNode) action).remove("command"); + limitations.add("Executable LSP commands are not exposed; only edit proposals are returned"); + } + } + if (operation.equals("prepareCallHierarchy") || operation.equals("incomingCalls") || operation.equals("outgoingCalls")) addItemIds(task, wire); + var output = new LinkedHashMap(); + output.put("operation", operation); output.put("result", mapper.convertValue(wire, Object.class)); + output.put("limitations", limitations); + return Collections.unmodifiableMap(output); + } finally { listening.cancel(true); } + } finally { workers.shutdownNow(); } + } + + private void addItemIds(TaskIdentity task, com.fasterxml.jackson.databind.JsonNode node) { + if (node.isObject() && node.has("uri") && node.has("selectionRange") && node.has("name") && node.has("kind")) { + var stored = items.computeIfAbsent(task, ignored -> new ConcurrentHashMap<>()); + if (stored.size() >= 1024) throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Too many hierarchy items for this task"); + String key = UUID.randomUUID().toString(); + stored.put(key, gson.fromJson(node.toString(), CallHierarchyItem.class)); + ((com.fasterxml.jackson.databind.node.ObjectNode) node).put("itemId", key); + } else if (node.isContainerNode()) node.forEach(child -> addItemIds(task, child)); + } + + private static void requireCapability(String operation, ServerCapabilities caps) { + Object capability = switch (operation) { + case "diagnostics" -> caps.getTextDocumentSync(); + case "hover" -> caps.getHoverProvider(); case "completion" -> caps.getCompletionProvider(); + case "signatureHelp" -> caps.getSignatureHelpProvider(); case "definition" -> caps.getDefinitionProvider(); + case "references" -> caps.getReferencesProvider(); case "documentSymbols" -> caps.getDocumentSymbolProvider(); + case "workspaceSymbols" -> caps.getWorkspaceSymbolProvider(); case "rename", "prepareRename" -> caps.getRenameProvider(); + case "codeActions" -> caps.getCodeActionProvider(); case "formatting" -> caps.getDocumentFormattingProvider(); + case "documentLinks" -> caps.getDocumentLinkProvider(); case "foldingRanges" -> caps.getFoldingRangeProvider(); + case "selectionRanges" -> caps.getSelectionRangeProvider(); case "prepareCallHierarchy", "incomingCalls", "outgoingCalls" -> caps.getCallHierarchyProvider(); + case "semanticTokens" -> caps.getSemanticTokensProvider(); default -> null; + }; + if (capability instanceof Either either) capability = either.isLeft() ? either.getLeft() : either.getRight(); + if (operation.equals("prepareRename") && (!(capability instanceof RenameOptions options) || !Boolean.TRUE.equals(options.getPrepareProvider()))) + throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise prepareRename"); + if (capability == null || Boolean.FALSE.equals(capability)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise " + operation); + } + + private static Position position(com.fasterxml.jackson.databind.JsonNode node, String text) { + if (!node.path("line").isIntegralNumber() || !node.path("character").isIntegralNumber() + || !node.path("line").canConvertToInt() || !node.path("character").canConvertToInt()) throw new IllegalArgumentException("UTF-16 position is required"); + int line = node.path("line").intValue(), character = node.path("character").intValue(); + String[] lines = text.split("\\r\\n|\\n|\\r", -1); + if (line < 0 || line >= lines.length || character < 0 || character > lines[line].length() + || character > 0 && character < lines[line].length() && Character.isHighSurrogate(lines[line].charAt(character - 1)) && Character.isLowSurrogate(lines[line].charAt(character))) + throw new IllegalArgumentException("Position is outside the saved document or splits a UTF-16 pair"); + return new Position(line, character); + } + + private static Range range(com.fasterxml.jackson.databind.JsonNode node, String text) { + var start = position(node.path("start"), text); var end = position(node.path("end"), text); + if (start.getLine() > end.getLine() || start.getLine() == end.getLine() && start.getCharacter() > end.getCharacter()) + throw new IllegalArgumentException("Range end precedes its start"); + return new Range(start, end); + } + + private static Path sourcePath(ProjectKnowledge.Context context, String uri) throws Exception { + final Path path; + try { path = Path.of(URI.create(uri)).toRealPath(); } + catch (RuntimeException | java.io.IOException invalid) { throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Source URI is not an accessible local project/dependency file"); } + boolean scope = path.startsWith(context.projectRoot()) || context.readOnlyRoots().stream().anyMatch(path::startsWith) + || context.libraries().stream().flatMap(lib -> lib.roots().stream()).anyMatch(path::startsWith); + boolean source = context.languages().stream().flatMap(lang -> lang.extensions().stream()).anyMatch(extension -> path.getFileName().toString().endsWith("." + extension)); + if (!scope || !source || !Files.isRegularFile(path)) throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "URI is outside the known source scope"); + return path; + } + + private static void requireEditable(ProjectKnowledge.Context context, String uri) throws Exception { + Path path = sourcePath(context, uri); + if (!path.startsWith(context.projectRoot()) || context.readOnlyRoots().stream().anyMatch(path::startsWith)) + throw failure(AutomationFailure.Code.READ_ONLY_SCOPE, "LSP edit proposal targets a read-only SDK/dependency"); + } + + private static void validateEdits(ProjectKnowledge.Context context, com.fasterxml.jackson.databind.JsonNode node) throws Exception { + if (node.isObject()) { + if (node.has("changes")) { + var fields = node.path("changes").fieldNames(); + while (fields.hasNext()) requireEditable(context, fields.next()); + } + if (node.has("textDocument") && node.has("edits")) requireEditable(context, node.path("textDocument").path("uri").asText()); + if (node.has("kind") && Set.of("create", "rename", "delete").contains(node.path("kind").asText())) + throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP file operations are not exposed"); + } + if (node.isContainerNode()) for (var child : node) validateEdits(context, child); + } + + private static T await(CompletableFuture future, long deadline) throws Exception { + try { return future.get(Math.max(1, deadline - System.nanoTime()), TimeUnit.NANOSECONDS); } + catch (ExecutionException failure) { + if (failure.getCause() instanceof org.eclipse.lsp4j.jsonrpc.ResponseErrorException response) { + int code = response.getResponseError().getCode(); + if (code == -32602) throw new IllegalArgumentException("LSP rejected query parameters"); + if (code == -32601 || code == -32600) + throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, response.getResponseError().getMessage()); + } + throw failure; + } + catch (Exception failure) { future.cancel(true); throw failure; } + } + private static AutomationException failure(AutomationFailure.Code code, String message) { return new AutomationException(code, message); } +} diff --git a/prometeu-app/src/main/java/p/studio/app/lsp/LspLifecycleAdapter.java b/prometeu-app/src/main/java/p/studio/app/lsp/LspLifecycleAdapter.java index a1aef156..5065659f 100644 --- a/prometeu-app/src/main/java/p/studio/app/lsp/LspLifecycleAdapter.java +++ b/prometeu-app/src/main/java/p/studio/app/lsp/LspLifecycleAdapter.java @@ -10,6 +10,7 @@ import java.util.Objects; public final class LspLifecycleAdapter implements LspLifecyclePort { private final LspServerLifecycle lifecycle; + private final java.util.Map bindings = new java.util.concurrent.ConcurrentHashMap<>(); public LspLifecycleAdapter(LspServerLifecycle lifecycle) { this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle"); @@ -17,19 +18,26 @@ public final class LspLifecycleAdapter implements LspLifecyclePort { @Override public void boot(ProjectReference project) { - lifecycle.bootServer(LspServerConfiguration.defaults(), context(project)); + var binding = context(project); + lifecycle.bootServer(LspServerConfiguration.builder().endpoint( + new p.studio.lsp.messages.LspServerEndpoint("127.0.0.1", 0)).build(), binding); + bindings.put(project.rootPath().toAbsolutePath().normalize(), binding); } @Override public void shutdown(ProjectReference project) { - lifecycle.shutdownServer(context(project)); + var binding = bindings.remove(project.rootPath().toAbsolutePath().normalize()); + if (binding != null) lifecycle.shutdownServer(binding); } - private static LspProjectContext context(ProjectReference project) { + static LspProjectContext context(ProjectReference project) { final var safeProject = Objects.requireNonNull(project, "project"); + final java.nio.file.Path root; + try { root = safeProject.rootPath().toRealPath(); } + catch (java.io.IOException failure) { throw new IllegalStateException("Project root unavailable", failure); } return new LspProjectContext( - safeProject.rootPath().toAbsolutePath().normalize().toString(), + root.toString(), safeProject.languageId(), - safeProject.rootPath()); + root); } } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpLanguageTools.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpLanguageTools.java new file mode 100644 index 00000000..1a81f030 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpLanguageTools.java @@ -0,0 +1,18 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.LanguageQueries; +import java.nio.file.Path; +import java.util.Map; +import java.util.function.Function; + +public final class McpLanguageTools { + private McpLanguageTools() {} + public static Map> handlers(LanguageQueries language, ObjectMapper mapper) { + return Map.of("studio_language_query", arguments -> McpToolResult.success(mapper, mapper.valueToTree( + language.query(Path.of(arguments.path("projectRoot").asText()), arguments.path("taskId").asText(), + arguments.path("operation").asText(), mapper.convertValue(arguments.path("parameters"), + new com.fasterxml.jackson.core.type.TypeReference>() {}))))); + } +} diff --git a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json index 276b109e..9e5bb926 100644 --- a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json +++ b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json @@ -573,7 +573,7 @@ }, "exampleValue": { "operation": "definition", - "locations": [], + "result": [], "limitations": [] } }, 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 dc6a5dad..f0f6ded7 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -30,9 +30,10 @@ 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(2, tools.size()); + org.junit.jupiter.api.Assertions.assertEquals(3, 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(executor.isShutdown()); assertFalse(mcp.isRunning()); diff --git a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java new file mode 100644 index 00000000..ea648396 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java @@ -0,0 +1,210 @@ +package p.studio.app.lsp; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.api.session.ProjectSession; +import p.studio.app.compiler.CompilerProjectKnowledge; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.core.language.TaskLanguageQueries; +import p.studio.core.project.*; +import p.studio.core.session.DefaultProjectSessionFactory; +import p.studio.lsp.services.LspServerLifecycleImpl; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +class AutomationLspQueriesTest { + @TempDir Path temporary; + final ObjectMapper mapper = new ObjectMapper(); + final ExecutorService workers = Executors.newCachedThreadPool(); + final LspServerLifecycleImpl lifecycle = new LspServerLifecycleImpl(); + ProjectSession session; + TaskLanguageQueries queries; + final ProjectAccessRegistry access = new ProjectAccessRegistry(); + Path root, source; + String task; + static final String CODE = "fn helper() -> int { return 1; }\nfn main() -> int { return helper(); }\n"; + + @BeforeEach void open() throws Exception { + root = Files.createDirectory(temporary.resolve("app")).toRealPath(); + source = Files.createDirectories(root.resolve("src")).resolve("main.pbs"); + manifest(root, "app", List.of()); + Files.writeString(source, CODE); + Files.writeString(source.resolveSibling("mod.barrel"), "pub fn helper() -> int;\npub fn main() -> int;\n"); + var setup = new ProjectLocalStudioSetupStore(mapper); + var catalog = new ProjectCatalogService(temporary, mapper, setup); + session = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup, + new LspLifecycleAdapter(lifecycle), access, new ExecutorOperationExecutor(workers)).open(catalog.openProject(root)); + var knowledge = new CompilerProjectKnowledge(access, catalog, mapper); + queries = new TaskLanguageQueries(access, new AutomationLspQueries(lifecycle, catalog, knowledge, mapper)); + } + @AfterEach void close() { if (session != null) session.close(); workers.shutdownNow(); } + void acquire() { + assertTrue(session.automation().grant(false).toCompletableFuture().join().success()); + task = session.automation().acquire().task().value(); + } + JsonNode query(String operation, Map parameters) { + return mapper.valueToTree(queries.query(root, task, operation, parameters)); + } + Map at(int line, int character) { + return Map.of("uri", source.toUri().toString(), "position", Map.of("line", line, "character", character)); + } + @Test void diagnosticsAndNavigationSeeSavedChangesOverTheActualServer() throws Exception { + acquire(); + assertTrue(query("diagnostics", at(0, 0)).path("result").isArray()); + var definition = query("definition", at(1, 26)).path("result"); + assertFalse(definition.isEmpty(), definition.toString()); + assertEquals(source.toUri().toString(), definition.get(0).path("uri").asText()); + Files.writeString(source, "fn main( {"); + assertFalse(query("diagnostics", at(0, 0)).path("result").isEmpty()); + Files.writeString(source, CODE.replace("helper", "renamed")); + Files.writeString(source.resolveSibling("mod.barrel"), "pub fn renamed() -> int;\npub fn main() -> int;\n"); + var symbols = query("documentSymbols", at(0, 0)).path("result"); + assertTrue(symbols.toString().contains("renamed"), symbols.toString()); + assertFalse(symbols.toString().contains("helper"), symbols.toString()); + } + @Test void proposalsDoNotWriteFilesAndQueriesCoverAdvertisedOperations() throws Exception { + acquire(); + for (String operation : List.of("hover", "completion", "signatureHelp", "references", "prepareRename", "semanticTokens")) + assertEquals(operation, query(operation, at(1, 26)).path("operation").asText()); + for (String operation : List.of("documentLinks", "foldingRanges", "formatting")) + assertEquals(operation, query(operation, at(0, 0)).path("operation").asText()); + assertEquals("workspaceSymbols", query("workspaceSymbols", Map.of("query", "helper")).path("operation").asText()); + var rename = new HashMap<>(at(1, 26)); rename.put("newName", "renamed"); + assertTrue(query("rename", rename).path("result").has("changes")); + assertEquals(CODE, Files.readString(source)); + var selections = Map.of("uri", source.toUri().toString(), "positions", List.of(Map.of("line", 0, "character", 4))); + assertEquals("selectionRanges", query("selectionRanges", selections).path("operation").asText()); + var actions = Map.of("uri", source.toUri().toString(), "range", Map.of("start", Map.of("line", 0, "character", 0), "end", Map.of("line", 0, "character", 10))); + assertEquals("codeActions", query("codeActions", actions).path("operation").asText()); + } + @Test void hierarchyIdsBelongToTheTaskAndDisappearOnReturn() { + acquire(); + var prepared = query("prepareCallHierarchy", at(0, 4)).path("result"); + assertFalse(prepared.isEmpty(), prepared.toString()); + String id = prepared.get(0).path("itemId").asText(); + assertFalse(id.isBlank()); + assertFalse(query("incomingCalls", Map.of("itemId", id)).path("result").isEmpty()); + assertEquals("outgoingCalls", query("outgoingCalls", Map.of("itemId", id)).path("operation").asText()); + session.automation().reclaim().toCompletableFuture().join(); + acquire(); + assertThrows(IllegalArgumentException.class, () -> query("incomingCalls", Map.of("itemId", id))); + } + @Test void admissionUnsupportedOperationsAndSourceScopeAreExplicit() throws Exception { + assertThrows(ControlDeniedException.class, () -> queries.query(root, "ungranted", "diagnostics", at(0, 0))); + acquire(); + assertThrows(ControlDeniedException.class, () -> queries.query(root, "wrong-task", "diagnostics", at(0, 0))); + assertEquals(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, assertThrows(AutomationException.class, + () -> query("typeHierarchy", at(0, 0))).failure().code()); + Path outside = temporary.resolve("outside.pbs"); Files.writeString(outside, CODE); + assertEquals(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, assertThrows(AutomationException.class, + () -> query("diagnostics", Map.of("uri", outside.toUri().toString()))).failure().code()); + assertThrows(IllegalArgumentException.class, () -> query("definition", at(999, 0))); + var context = LspLifecycleAdapter.context(session.projectReference()); + var endpoint = lifecycle.endpoint(context).orElseThrow(); + session.close(); session = null; + assertTrue(lifecycle.endpoint(context).isEmpty()); + assertThrows(java.io.IOException.class, () -> new java.net.Socket(endpoint.host(), endpoint.port())); + assertEquals(AutomationFailure.Code.PROJECT_NOT_OPEN, assertThrows(AutomationException.class, + () -> query("diagnostics", at(0, 0))).failure().code()); + } + + @Test void mcpDispatchPreservesTaskFailuresAndReturnsNeutralLspResults() { + var tools = new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(mapper), mapper, + p.studio.app.mcp.McpLanguageTools.handlers(queries, mapper)); + var arguments = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "missing").put("operation", "diagnostics"); + arguments.putObject("parameters").put("uri", source.toUri().toString()); + var denied = tools.call("studio_language_query", arguments).wire(); + assertEquals("INVALID_TASK", denied.path("structuredContent").path("error").path("code").asText()); + acquire(); arguments.put("taskId", task); + var success = tools.call("studio_language_query", arguments).wire(); + assertFalse(success.path("isError").asBoolean(), success.toString()); + assertTrue(success.path("structuredContent").path("value").path("result").isArray()); + session.automation().reclaim().toCompletableFuture().join(); + assertEquals("INVALID_TASK", tools.call("studio_language_query", arguments).wire().path("structuredContent").path("error").path("code").asText()); + } + + @Test void authenticatedHttpToolUsesTheRealLspButDoesNotGrantTaskAuthority() throws Exception { + var tools = new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(mapper), mapper, + p.studio.app.mcp.McpLanguageTools.handlers(queries, mapper)); + try (var server = new p.studio.app.mcp.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 setup = initialize.putObject("params").put("protocolVersion", "2025-06-18"); + setup.putObject("capabilities"); setup.putObject("clientInfo").put("name", "language-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")); + var request = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call"); + var args = request.putObject("params").put("name", "studio_language_query").putObject("arguments") + .put("projectRoot", root.toString()).put("taskId", "ungranted").put("operation", "documentSymbols"); + args.putObject("parameters").put("uri", source.toUri().toString()); + var denied = mapper.readTree(post(client, server, connection, request).body()).path("result"); + assertEquals("INVALID_TASK", denied.path("structuredContent").path("error").path("code").asText()); + acquire(); args.put("taskId", task); + var result = mapper.readTree(post(client, server, connection, request).body()).path("result"); + assertFalse(result.path("isError").asBoolean(), result.toString()); + assertTrue(result.path("structuredContent").path("value").path("result").toString().contains("helper")); + } + } + + private java.net.http.HttpResponse post(java.net.http.HttpClient client, p.studio.app.mcp.LocalMcpServer server, + String connection, JsonNode body) throws Exception { + var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(15)) + .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()); + } + + @Test void reclaimCancelsTheQueryAndEndsTaskResourcesAfterTheWorkerStops() throws Exception { + var entered = new CountDownLatch(1); + var stopped = new CountDownLatch(1); + var cleaned = new java.util.concurrent.atomic.AtomicBoolean(); + var slow = new TaskLanguageQueries(access, new p.studio.core.language.LanguageQueryPort() { + @Override public Map query(TaskIdentity task, String operation, Map params) throws Exception { + entered.countDown(); + try { new CountDownLatch(1).await(); return Map.of(); } + finally { stopped.countDown(); } + } + @Override public void endTask(TaskIdentity task) { assertEquals(0, stopped.getCount()); cleaned.set(true); } + }); + acquire(); + var pending = workers.submit(() -> slow.query(root, task, "diagnostics", at(0, 0))); + assertTrue(entered.await(2, TimeUnit.SECONDS)); + assertEquals(ControlResult.Status.BUSY, assertThrows(ControlDeniedException.class, + () -> queries.query(root, task, "diagnostics", at(0, 0))).status()); + assertTrue(session.automation().reclaim().toCompletableFuture().get(2, TimeUnit.SECONDS).success()); + assertThrows(ExecutionException.class, () -> pending.get(2, TimeUnit.SECONDS)); + assertTrue(cleaned.get()); + assertEquals(ControlState.MANUAL, session.automation().snapshot().state()); + } + @Test void externalDependencyNavigationIsReadableButRefactoringIsReadOnly() throws Exception { + Path lib = Files.createDirectories(temporary.resolve("lib")).toRealPath(); + manifest(lib, "lib", List.of()); + Path module = Files.createDirectories(lib.resolve("src/shared")); + Path declaration = module.resolve("main.pbs"); + Files.writeString(declaration, "fn answer() -> int { return 42; }\n"); + Files.writeString(module.resolve("mod.barrel"), "pub fn answer() -> int;\n"); + manifest(root, "app", List.of(Map.of("path", "../lib"))); + Files.createDirectories(root.resolve(".workspace/repos")); Files.writeString(root.resolve(".workspace/repos/registry.json"), "{}"); + Files.writeString(source, "import { answer } from @lib:shared;\nfn main() -> int { return answer(); }\n"); + Files.writeString(source.resolveSibling("mod.barrel"), "pub fn main() -> int;\n"); + acquire(); + var locations = query("definition", at(1, 26)).path("result"); + assertFalse(locations.isEmpty(), locations.toString()); + assertEquals(declaration.toUri().toString(), locations.get(0).path("uri").asText()); + assertEquals("documentSymbols", query("documentSymbols", Map.of("uri", declaration.toUri().toString())).path("operation").asText()); + assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class, + () -> query("formatting", Map.of("uri", declaration.toUri().toString()))).failure().code()); + var rename = new HashMap<>(at(1, 26)); rename.put("newName", "renamed"); + assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class, () -> query("rename", rename)).failure().code()); + } + private void manifest(Path path, String name, List dependencies) throws Exception { + mapper.writeValue(path.resolve("prometeu.json").toFile(), Map.of("name", name, "version", "1.0.0", "language", "pbs", "stdlib", "1", "target", "Game", "dependencies", dependencies)); + } +} diff --git a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java index fbbaa1b1..8ef66c98 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java @@ -13,7 +13,7 @@ class StudioBoundaryArchTest { static final ArchRule automationTransportStaysInTheApp = noClasses() .that().resideInAnyPackage("p.studio.api..", "p.studio.core..", "p.studio.ui..") .should().dependOnClassesThat().resideInAnyPackage( - "p.studio.app.mcp..", "com.sun.net.httpserver..", "io.modelcontextprotocol..") + "p.studio.app.mcp..", "p.studio.app.lsp..", "org.eclipse.lsp4j..", "com.sun.net.httpserver..", "io.modelcontextprotocol..") .because("DEC-0060 confines MCP and HTTP transport to application adapters"); @ArchTest diff --git a/prometeu-lsp/prometeu-lsp-api/src/main/java/p/studio/lsp/api/LspServerLifecycle.java b/prometeu-lsp/prometeu-lsp-api/src/main/java/p/studio/lsp/api/LspServerLifecycle.java index 564020b8..81a02ea1 100644 --- a/prometeu-lsp/prometeu-lsp-api/src/main/java/p/studio/lsp/api/LspServerLifecycle.java +++ b/prometeu-lsp/prometeu-lsp-api/src/main/java/p/studio/lsp/api/LspServerLifecycle.java @@ -7,4 +7,8 @@ public interface LspServerLifecycle { void bootServer(LspServerConfiguration serverConfiguration, LspProjectContext context); void shutdownServer(LspProjectContext context); + + default java.util.Optional endpoint(LspProjectContext context) { + return java.util.Optional.empty(); + } } diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java index 9a85283d..4e629f9a 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java @@ -47,6 +47,12 @@ public final class LspServerLifecycleImpl implements LspServerLifecycle { closeQuietly(host); } + @Override + public java.util.Optional endpoint(LspProjectContext context) { + var host = activeServers.get(context.projectKey()); + return host == null || !host.matches(context) ? java.util.Optional.empty() : host.endpoint(); + } + private static void closeQuietly(final TcpLspServerHost host) { try { host.close(); diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/TcpLspServerHost.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/TcpLspServerHost.java index 0f7edc60..d79ed593 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/TcpLspServerHost.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/TcpLspServerHost.java @@ -24,6 +24,7 @@ public final class TcpLspServerHost { private volatile boolean closed; private volatile ServerSocket serverSocket; private volatile Thread acceptThread; + private final java.util.Set clients = java.util.concurrent.ConcurrentHashMap.newKeySet(); public TcpLspServerHost( final LspServerConfiguration serverConfiguration, @@ -59,6 +60,8 @@ public final class TcpLspServerHost { while (!closed) { try { final Socket socket = serverSocket.accept(); + clients.add(socket); + if (closed) { clients.remove(socket); socket.close(); break; } clientExecutor.submit(() -> handleClient(socket)); } catch (IOException exception) { if (!closed) { @@ -74,14 +77,21 @@ public final class TcpLspServerHost { final Launcher launcher = LSPLauncher.createServerLauncher( server, socket.getInputStream(), - socket.getOutputStream()); + socket.getOutputStream(), clientExecutor, consumer -> consumer); server.connect(launcher.getRemoteProxy()); launcher.startListening().get(); } catch (Exception exception) { - throw new IllegalStateException("LSP client failed", exception); - } + if (!closed && !socket.isClosed()) throw new IllegalStateException("LSP client failed", exception); + } finally { clients.remove(socket); } } + public synchronized java.util.Optional endpoint() { + return closed || serverSocket == null ? java.util.Optional.empty() : java.util.Optional.of( + new p.studio.lsp.messages.LspServerEndpoint(serverSocket.getInetAddress().getHostAddress(), serverSocket.getLocalPort())); + } + + public boolean matches(LspProjectContext project) { return context.equals(project); } + public synchronized void close() throws Exception { if (closed) { return; @@ -93,6 +103,8 @@ public final class TcpLspServerHost { if (acceptThread != null) { acceptThread.interrupt(); } + for (var socket : clients) { try { socket.close(); } catch (IOException ignored) {} } + clients.clear(); clientExecutor.shutdownNow(); } } diff --git a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java new file mode 100644 index 00000000..9e8ba13d --- /dev/null +++ b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java @@ -0,0 +1,37 @@ +package p.studio.lsp.services; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.lsp.messages.*; +import java.nio.file.Path; +import java.net.Socket; +import static org.junit.jupiter.api.Assertions.*; + +class LspServerLifecycleTest { + @TempDir Path temporary; + + @Test void projectEndpointsAreIndependentAndShutdownClosesConnectedSockets() throws Exception { + var lifecycle = new LspServerLifecycleImpl(); + var first = new LspProjectContext("first", "pbs", temporary); + var second = new LspProjectContext("second", "pbs", temporary.resolve("second")); + var configuration = LspServerConfiguration.builder().endpoint(new LspServerEndpoint("127.0.0.1", 0)).build(); + lifecycle.bootServer(configuration, first); lifecycle.bootServer(configuration, second); + try { + var endpoint = lifecycle.endpoint(first).orElseThrow(); + assertNotEquals(endpoint.port(), lifecycle.endpoint(second).orElseThrow().port()); + assertTrue(lifecycle.endpoint(new LspProjectContext("first", "other-language", temporary)).isEmpty()); + try (var socket = new Socket(endpoint.host(), endpoint.port())) { + socket.setSoTimeout(2000); + String request = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"rootUri\":\"" + temporary.toUri() + "\",\"capabilities\":{}}}"; + byte[] body = request.getBytes(java.nio.charset.StandardCharsets.UTF_8); + socket.getOutputStream().write(("Content-Length: " + body.length + "\r\n\r\n").getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + socket.getOutputStream().write(body); socket.getOutputStream().flush(); + assertNotEquals(-1, socket.getInputStream().read()); + lifecycle.shutdownServer(first); + socket.getInputStream().readAllBytes(); // Buffered reply drains, then EOF; no abandoned client connection. + assertTrue(lifecycle.endpoint(first).isEmpty()); + assertTrue(lifecycle.endpoint(second).isPresent()); + } + } finally { lifecycle.shutdownServer(first); lifecycle.shutdownServer(second); } + } +} 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 dc46493b..45474d50 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 @@ -17,4 +17,6 @@ public interface AutomationSession { OperationHandle submit(TaskIdentity task, String summary, Callable work); void attachRuntime(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/LanguageQueries.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/LanguageQueries.java new file mode 100644 index 00000000..1d9bbbcc --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/LanguageQueries.java @@ -0,0 +1,9 @@ +package p.studio.api.automation; + +import java.nio.file.Path; +import java.util.Map; + +/** Neutral language query boundary. Values contain only JSON-compatible maps, lists and scalars. */ +public interface LanguageQueries { + Map query(Path projectRoot, String taskId, String operation, Map parameters); +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/language/LanguageQueryPort.java b/prometeu-studio-core/src/main/java/p/studio/core/language/LanguageQueryPort.java new file mode 100644 index 00000000..cb066a75 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/language/LanguageQueryPort.java @@ -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 query(TaskIdentity task, String operation, Map parameters) throws Exception; + void endTask(TaskIdentity task); +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java b/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java new file mode 100644 index 00000000..01b4cd9e --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java @@ -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 registered = ConcurrentHashMap.newKeySet(); + + public TaskLanguageQueries(ProjectAccessRegistry projects, LanguageQueryPort language) { + this.projects = Objects.requireNonNull(projects); this.language = Objects.requireNonNull(language); + } + + @Override public Map query(Path root, String taskId, String operation, Map 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>(); + 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(); + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java index 555e5f0c..0f9cc1ad 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java @@ -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 authority, BooleanSupplier available) {} + private record Entry(Supplier authority, BooleanSupplier available, p.studio.api.automation.AutomationSession automation) {} private final Map projects = new HashMap<>(); public OperationSubscription register(Path root, Supplier authority) { @@ -22,12 +22,27 @@ public final class ProjectAccessRegistry implements ProjectAccess { } public synchronized OperationSubscription register(Path root, Supplier authority, BooleanSupplier available) { + return register(root, authority, available, null); + } + + public synchronized OperationSubscription register(Path root, Supplier 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); 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 9b1a3544..6a85eb47 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 @@ -25,6 +25,12 @@ public final class DefaultAutomationSession implements AutomationSession { private List diagnostics = List.of(); private CompletableFuture returning; private final List manualCancellation = new ArrayList<>(); + private final List taskCleanup = new ArrayList<>(); + + @Override public synchronized void onTaskEnd(TaskIdentity identity, Runnable cleanup) { + requireTask(identity); + taskCleanup.add(Objects.requireNonNull(cleanup)); + } private CompletableFuture manualIdle = CompletableFuture.completedFuture(null); public DefaultAutomationSession(Path root, OperationExecutor executor) { @@ -150,6 +156,7 @@ public final class DefaultAutomationSession implements AutomationSession { final List cancellations; final List participants; final CompletableFuture idle; + final List 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 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); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index 3cf66f3d..4d4e76dd 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -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); diff --git a/prometeu-studio-core/src/test/java/p/studio/core/StudioModularityTest.java b/prometeu-studio-core/src/test/java/p/studio/core/StudioModularityTest.java index 306731fd..6c82e0ea 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/StudioModularityTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/StudioModularityTest.java @@ -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())); } diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java index b1533bc1..a48470ae 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java @@ -18,6 +18,23 @@ class DefaultAutomationSessionTest { ControlResult await(CompletionStage 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()); From 20bbbd26bd7427b2790d2e0e94ca37fe7eb7bdde Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 10:26:19 +0100 Subject: [PATCH 06/15] expose task control and deduplicated operations through MCP --- ...CP Tools and Project Knowledge Contract.md | 50 ++- .../app/StudioApplicationConfiguration.java | 14 +- .../java/p/studio/app/mcp/McpTaskTools.java | 97 ++++++ .../java/p/studio/app/mcp/McpToolResult.java | 8 + .../StudioApplicationConfigurationTest.java | 6 +- .../p/studio/app/mcp/McpTaskToolsTest.java | 287 ++++++++++++++++++ .../api/automation/AutomationSession.java | 2 + .../p/studio/api/automation/TaskTools.java | 21 ++ .../api/automation/TrackedOperation.java | 3 +- .../studio/core/runtime/HeadlessGateway.java | 18 ++ .../session/DefaultAutomationSession.java | 23 +- .../studio/core/session/DefaultTaskTools.java | 234 ++++++++++++++ .../core/shipper/SavedProjectPreparation.java | 12 + .../core/shipper/StudioShipperService.java | 12 +- 14 files changed, 775 insertions(+), 12 deletions(-) create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpTaskTools.java create mode 100644 prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/TaskTools.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/runtime/HeadlessGateway.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/shipper/SavedProjectPreparation.java 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(); From 9592c9b274de0523a7642277c8c34cd2a253ccb6 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 10:36:50 +0100 Subject: [PATCH 07/15] connect DEV to live MCP configuration and verify tool conformance --- README.md | 35 ++++++- ...CP Tools and Project Knowledge Contract.md | 36 +++++++- .../app/StudioApplicationConfiguration.java | 10 +- .../java/p/studio/app/StudioUiFactory.java | 6 +- .../java/p/studio/app/mcp/LocalMcpServer.java | 13 ++- .../p/studio/app/mcp/McpConnectionGuide.java | 50 ++++++++++ .../java/p/studio/app/DevDesktopTest.java | 55 +++++++++++ .../app/mcp/McpConnectionGuideTest.java | 52 +++++++++++ .../p/studio/app/mcp/McpTaskToolsTest.java | 91 +++++++++++++++++++ .../api/automation/AgentConnectionGuide.java | 21 +++++ .../studio/ui/javafx/utilities/i18n/I18n.java | 1 + .../p/studio/ui/javafx/window/MainView.java | 4 +- .../window/StudioWindowCoordinator.java | 6 +- .../javafx/workspaces/dev/DevWorkspace.java | 45 ++++++++- .../main/resources/i18n/messages.properties | 5 +- .../resources/i18n/messages_pt_BR.properties | 5 +- 16 files changed, 417 insertions(+), 18 deletions(-) create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java create mode 100644 prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java diff --git a/README.md b/README.md index 0a339e57..65a6da41 100644 --- a/README.md +++ b/README.md @@ -21,14 +21,47 @@ The root project is a monorepo with these main areas: ## Current Product Shape -The Studio shell currently organizes the product around three workspaces: +The Studio shell currently organizes the product around four workspaces: - Assets - Debug +- DEV (external-agent authorization and observation) - Shipper At runtime, the app boots an embedded packer, restores project-local Studio state, and opens the Studio launcher window. Project creation currently scaffolds a Prometeu workspace with `prometeu.json`, `src/`, `assets/`, `build/`, `cartridge/`, `.workspace/`, and local Studio metadata. +## External Coding Agents (MCP) + +Open a project and select **DEV → Copy MCP configuration**. The copied JSON is a +provider-neutral connection descriptor: use its `url` and `headers.Authorization` +in your external client's Streamable HTTP MCP setup, and provide its `projectRoot` +and instructions to the agent. Adapt the configuration syntax to your client; +there is no embedded chat or provider-specific setup wizard. + +Keep the descriptor/token private and out of versioned files and logs. The endpoint +is local to this computer. After restarting Studio, copy it again and update the +client: both the port and token are ephemeral. Copying or connecting does not +authorize edits or start a task. + +1. Connect, discover tools, read project context and applicable language/SDK references. +2. In DEV, grant control (save all first if prompted). Active Debug prevents granting. +3. The agent acquires a task, edits saved project files using its own tools, and + validates through LSP/build. SDK and external libraries are consultable, read-only. +4. Poll operations by operationId or clientRequestId. Recover a lost start receipt + by lookup; never retry frame advancement blindly with a new ID. +5. The agent explicitly releases control. To interrupt, use DEV's reclaim button + and stop the external client separately: Studio cannot prevent its direct file writes. + +The current production tools cover context, references, task control, LSP, +build/pack and operation lookup/cancellation. Headless tool handlers are tested, +but remain undiscoverable until the real runtime gateway is composed. DEV is an +observation panel, not manual Play/input for the agent's session; **Debug** retains +the human testing workflow. Edits are preserved on cancellation; Git/review/recovery +remain the developer's responsibility. + +See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) +for schemas, authorization, limits and delivery boundaries. + ## Requirements - JDK 21 or newer recommended for local development 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 c1f30af0..5758e392 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 @@ -62,6 +62,35 @@ and [tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tool contracts. Optional SSE, server-initiated requests, sampling, prompts, resource subscriptions and list-change notifications are not advertised. +### 1.1 DEV Connection Assistance + +DEV displays the current endpoint without credentials and provides **Copy MCP +configuration** for an open project. The neutral `AgentConnectionGuide` supplies +availability and a deliberate clipboard export; JavaFX MUST NOT depend on the +HTTP server or keep credentials in labels, diagnostics, project state or history. +Connection lifecycle changes refresh availability. A closed project or stopped +server cannot export a descriptor. Unloading DEV only unsubscribes presentation +listeners; it does not stop the endpoint or revoke project authority. + +The copied text is a provider-neutral JSON descriptor with `transport` set to +`streamable-http`, the live `url`, `headers.Authorization`, canonical `projectRoot` +and `instructions`. It is not a promise of a drop-in configuration format for +every external client. The developer maps URL/header fields to that client's MCP +configuration; a provider-specific wizard remains out of scope. The secret is +materialized only for explicit copying and MUST NOT be written to versioned files +or logs. Clipboard success/failure feedback MUST NOT repeat credential-bearing +content or raw exceptions. The clipboard itself is a deliberate secret export. + +Copied instructions and MCP initialization guidance direct the client to discover +actual tools, read project context and applicable language/SDK/library references, +wait for human grant before acquisition, edit saved files within project scope, +validate with LSP/build, recover operation receipts by clientRequestId and release +explicitly. Missing language support is a reported limitation, not a PBS fallback. +They also explain that SDK/external libraries are read-only, revocation cannot +stop external file writes, copying grants no authority, and a Studio restart +requires fresh endpoint/token configuration. No provider or model is required +to test this guidance and the MCP service contract. + ## 2. Identity and Admission All tool inputs require `projectRoot`: an absolute filesystem root resolving to @@ -405,6 +434,9 @@ and `studio_language_query`, plus control acquire/release, build start and opera 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 +DEV configuration-copy is connected as of step 21. The automated HTTP conformance +gate exercises all 17 tool contracts using real project knowledge/LSP and test-only +build/runtime ports; a separate HTTP test uses the real compiler/packer. This +completes MCP-phase conformance, not real-process or external-agent acceptance. +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 eb57a3b1..461849ca 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -281,13 +281,13 @@ public class StudioApplicationConfiguration { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory, executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, windowStateStore, - activityHistoryStore); + activityHistoryStore, connectionGuide); } @Bean @@ -335,6 +335,12 @@ public class StudioApplicationConfiguration { return new p.studio.app.mcp.LocalMcpServer(mapper, tools); } + @Bean + p.studio.api.automation.AgentConnectionGuide connectionGuide(p.studio.app.mcp.LocalMcpServer server, + p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper) { + return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper); + } + private static Path resolveDefaultProjectsRoot() { Path cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize(); while (cursor != null) { diff --git a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java index 898eef58..19d30390 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java @@ -56,6 +56,7 @@ public final class StudioUiFactory { private final SceneBankWorkflow sceneBankWorkflow; private final WindowStateStore windowStateStore; private final ProjectActivityHistoryStore activityHistoryStore; + private final p.studio.api.automation.AgentConnectionGuide connectionGuide; public StudioUiFactory( ProjectCatalog projectCatalog, @@ -82,7 +83,8 @@ public final class StudioUiFactory { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { + this.connectionGuide = Objects.requireNonNull(connectionGuide); this.projectCatalog = Objects.requireNonNull(projectCatalog, "projectCatalog"); this.knownProjects = Objects.requireNonNull(knownProjects, "knownProjects"); this.languageCatalog = Objects.requireNonNull(languageCatalog, "languageCatalog"); @@ -116,6 +118,6 @@ public final class StudioUiFactory { assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, windowStateStore, - activityHistoryStore); + activityHistoryStore, connectionGuide); } } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java b/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java index b1b96e78..a9b19dee 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java @@ -26,6 +26,15 @@ public final class LocalMcpServer implements AutoCloseable { private ExecutorService executor; private ScheduledExecutorService deadlines; private volatile Connection connection; + private final java.util.List connectionListeners = new CopyOnWriteArrayList<>(); + + public p.studio.api.operation.OperationSubscription onConnectionChanged(Runnable listener) { + connectionListeners.add(listener); notifyConnectionListener(listener); + return () -> connectionListeners.remove(listener); + } + private static void notifyConnectionListener(Runnable listener) { + try { listener.run(); } catch (RuntimeException ignored) { /* Observation cannot change lifecycle. */ } + } public LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools) { this.mapper = mapper.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) @@ -47,6 +56,7 @@ public final class LocalMcpServer implements AutoCloseable { next.setExecutor(workers); next.start(); executor = workers; server = next; + connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } catch (RuntimeException failure) { next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null; throw failure; @@ -62,6 +72,7 @@ public final class LocalMcpServer implements AutoCloseable { if (server == null) return; connection = null; server.stop(0); server = null; sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow(); + connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } /** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */ @@ -144,7 +155,7 @@ public final class LocalMcpServer implements AutoCloseable { var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION); result.putObject("capabilities").putObject("tools").put("listChanged", false); result.putObject("serverInfo").put("name", "prometeu-studio-mcp").put("version", "1.0"); - result.put("instructions", "Read project context and indexed references. Human grant in DEV precedes acquisition. Edit saved project files with your native tools, never SDK/external libraries. Validate with LSP/build and explicitly release. Studio revocation does not stop your external file writes. Reconnect with new configuration after Studio restart."); + result.put("instructions", McpConnectionGuide.INSTRUCTIONS); send(exchange, 200, response(id, result)); return; } if (initialized == null) { empty(exchange, 400); return; } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java new file mode 100644 index 00000000..ac096304 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java @@ -0,0 +1,50 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.AgentConnectionGuide; +import p.studio.api.operation.OperationSubscription; +import p.studio.core.project.ProjectAccessRegistry; +import java.nio.file.Path; +import java.util.Optional; + +/** Builds a provider-neutral connection descriptor from the live server, only on explicit export. */ +public final class McpConnectionGuide implements AgentConnectionGuide { + public static final String INSTRUCTIONS = """ + Configure your external coding client's MCP connection using the url and Authorization header below. + This is a provider-neutral descriptor, not a provider-specific configuration file. + Keep the token private; do not commit this descriptor, write it into project files or include it in logs. + Connect and list available tools. Read studio_project_context for the explicit projectRoot and consult + studio_reference_read for the declared languages, SDK and libraries before editing as needed. + Do not assume PBS or another language when support/documentation is missing; report the limitation. + Wait for the developer to grant control in DEV, then call studio_control_acquire. Copying or connecting + does not grant permission. Use the returned taskId for all work and operate only on this project. + Edit saved project files with your native tools; SDK and external libraries are read-only. + Validate saved changes with studio_language_query and studio_build_start. Poll studio_operation_get. + Supply a unique clientRequestId per intended build/advance. Recover lost responses by lookup using + clientRequestId; do not blindly repeat frame advancement with a new ID. Cancellation acknowledgement + is not worker termination. Use only tools/capabilities actually advertised by this running Studio. + Observe headless images/state when those tools are available, and explicitly studio_control_release + when finished. On revocation stop external edits too: Studio cannot stop your native file writes. + Existing edits are preserved. Git/review/recovery remain the developer's responsibility. + Recopy and update your client's connection after Studio restart: endpoint and token are ephemeral. + """; + private final LocalMcpServer server; + private final ProjectAccessRegistry projects; + private final ObjectMapper mapper; + public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper) { + this.server = server; this.projects = projects; this.mapper = mapper; + } + @Override public Optional endpoint() { + try { return Optional.of(server.connection().endpoint().toString()); } + catch (IllegalStateException unavailable) { return Optional.empty(); } + } + @Override public String configuration(Path root) { + Path canonical = projects.requireOpenRoot(root); + var live = server.connection(); + var value = mapper.createObjectNode().put("transport", "streamable-http").put("url", live.endpoint().toString()); + value.putObject("headers").put("Authorization", live.authorizationHeader()); + value.put("projectRoot", canonical.toString()).put("instructions", INSTRUCTIONS); + return value.toPrettyString(); + } + @Override public OperationSubscription subscribe(Runnable changed) { return server.onConnectionChanged(changed); } +} diff --git a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java index a44980ea..eeb2d185 100644 --- a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java @@ -120,6 +120,61 @@ class DevDesktopTest { }); } + @Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception { + var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + var projects = new p.studio.core.project.ProjectAccessRegistry(); + var savedClipboard = new java.util.HashMap(); + var copied = new java.util.concurrent.atomic.AtomicReference(); + var view = new DevWorkspace[1]; var stage = new Stage[1]; + try (var pool = Executors.newSingleThreadExecutor(); + var server = new p.studio.app.mcp.LocalMcpServer(mapper, new p.studio.app.mcp.McpToolRegistry( + new p.studio.app.mcp.McpToolCatalog(mapper), mapper, java.util.Map.of()))) { + var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); + var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority); + var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper); + server.start(); + try { + fx(() -> { + var clipboard = javafx.scene.input.Clipboard.getSystemClipboard(); + clipboard.getContentTypes().forEach(type -> savedClipboard.put(type, clipboard.getContent(type))); + var project = new ProjectReference("Connection smoke", "1", "pbs", 1, ProjectTarget.Game, root); + view[0] = new DevWorkspace(project, authority, new I18nService(), new StudioEventBus(), guide); + stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show(); + view[0].load(); + var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); + button.fire(); copied.set(clipboard.getString()); + assertEquals(ControlState.MANUAL, authority.snapshot().state()); + assertEquals(server.connection().endpoint().toString(), ((Label) view[0].rootNode().lookup("#dev-mcp-endpoint")).getText()); + assertTrue(view[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label) + .noneMatch(n -> ((Label) n).getText().contains(server.connection().authorizationHeader()))); + }); + var first = mapper.readTree(copied.get()); + assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText())); + assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText()); + server.close(); + fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); + server.start(); authority.grant(false).toCompletableFuture().join(); + fx(() -> { + var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); + button.fire(); copied.set(javafx.scene.input.Clipboard.getSystemClipboard().getString()); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + }); + var next = mapper.readTree(copied.get()); + assertFalse(first.path("headers").equals(next.path("headers"))); + assertTrue(server.connection().authorizationHeader().equals(next.path("headers").path("Authorization").asText())); + authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); + fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); + } finally { + fx(() -> { + if (view[0] != null) view[0].unLoad(); + if (stage[0] != null) stage[0].close(); + javafx.scene.input.Clipboard.getSystemClipboard().setContent(savedClipboard); + }); + authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close(); + } + } + } + @Test void lockedUiBlocksMutationActionsButNotReadOnlyActions() throws Exception { fx(() -> { var root = new VBox(); var mutate = new Button("write"); var inspect = new Button("inspect"); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java new file mode 100644 index 00000000..b1f8d0fc --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java @@ -0,0 +1,52 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.api.automation.*; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; + +class McpConnectionGuideTest { + @TempDir Path root; + @Test void exportsLiveProjectDescriptorWithoutGrantAndTracksRestartWithoutRetainingSecrets() throws Exception { + var mapper = new ObjectMapper(); var projects = new ProjectAccessRegistry(); + try (var workers = Executors.newSingleThreadExecutor(); + var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) { + var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers)); + var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority); + var guide = new McpConnectionGuide(server, projects, mapper); + assertTrue(guide.endpoint().isEmpty()); + assertThrows(IllegalStateException.class, () -> guide.configuration(root)); + var notifications = new AtomicInteger(); + var subscription = guide.subscribe(notifications::incrementAndGet); + server.start(); assertEquals(2, notifications.get()); + var descriptor = mapper.readTree(guide.configuration(root)); + assertEquals(server.connection().endpoint().toString(), descriptor.path("url").asText()); + assertEquals(root.toRealPath().toString(), descriptor.path("projectRoot").asText()); + // Do not put bearer credentials into assertion diagnostics. + assertTrue(server.connection().authorizationHeader().equals(descriptor.path("headers").path("Authorization").asText())); + assertFalse(guide.toString().contains(descriptor.path("headers").path("Authorization").asText())); + assertEquals(ControlState.MANUAL, authority.snapshot().state()); + assertNull(authority.snapshot().task()); + for (var instruction : List.of("studio_project_context", "studio_reference_read", "studio_control_acquire", "studio_control_release", + "studio_language_query", "studio_build_start", "clientRequestId", "read-only", "restart", "native file writes")) + assertTrue(descriptor.path("instructions").asText().contains(instruction)); + var old = server.connection(); server.close(); assertEquals(3, notifications.get()); assertTrue(guide.endpoint().isEmpty()); + server.start(); assertEquals(4, notifications.get()); + var fresh = mapper.readTree(guide.configuration(root)); + assertTrue(fresh.path("headers").path("Authorization").asText().equals(server.connection().authorizationHeader())); + assertFalse(fresh.path("headers").path("Authorization").asText().equals(old.authorizationHeader())); + assertThrows(AutomationException.class, () -> guide.configuration(root.resolve("unopened"))); + authority.closeAsync().toCompletableFuture().join(); + assertThrows(AutomationException.class, () -> guide.configuration(root)); + registration.close(); subscription.close(); server.close(); assertEquals(4, notifications.get()); + } + } +} 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 index 575b3440..bebead92 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -238,6 +238,97 @@ class McpTaskToolsTest { } } } + @Test void allToolGroupsConformOverHttpWithRealLspAndTestOnlyRuntime() throws Exception { + Path source = Files.createDirectories(root.resolve("src")).resolve("main.pbs"); + Files.writeString(source, "fn main() -> int { return 1; }\n"); + var lifecycle = new p.studio.lsp.services.LspServerLifecycleImpl(); + var lsp = new p.studio.app.lsp.LspLifecycleAdapter(lifecycle); + var project = catalog.openProject(root); lsp.boot(project); + var knowledge = new p.studio.app.compiler.CompilerProjectKnowledge(access, catalog, mapper); + var language = new p.studio.core.language.TaskLanguageQueries(access, + new p.studio.app.lsp.AutomationLspQueries(lifecycle, catalog, knowledge, mapper)); + var handlers = new LinkedHashMap<>(McpTaskTools.handlers(service, mapper, true)); + handlers.putAll(McpProjectKnowledgeTools.handlers(knowledge, mapper)); + handlers.putAll(McpLanguageTools.handlers(language, mapper)); + try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers)); + var client = java.net.http.HttpClient.newHttpClient()) { + server.start(); + var unauthorized = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).POST(java.net.http.HttpRequest.BodyPublishers.ofString("{}")) + .timeout(java.time.Duration.ofSeconds(5)).build(); + 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()); + 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))); + error("NOT_GRANTED", httpCall(client, server, first, "studio_control_acquire", rootOnly())); + error("INVALID_TASK", httpCall(client, server, first, "studio_build_start", args().put("taskId", "missing").put("clientRequestId", "denied"))); + session.grant(false).toCompletableFuture().join(); + var a = workers.submit(() -> httpCall(client, server, first, "studio_control_acquire", rootOnly())); + var b = workers.submit(() -> httpCall(client, server, second, "studio_control_acquire", rootOnly())); + var results = List.of(a.get(5, TimeUnit.SECONDS), b.get(5, TimeUnit.SECONDS)); + assertEquals(1, results.stream().filter(r -> !r.path("isError").asBoolean()).count()); + task = value(results.stream().filter(r -> !r.path("isError").asBoolean()).findFirst().orElseThrow()).path("taskId").asText(); + var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString()); + value(httpCall(client, server, first, "studio_language_query", query)); + Files.writeString(source, "fn main( {"); + assertFalse(value(httpCall(client, server, first, "studio_language_query", query)).path("result").isEmpty()); + Files.writeString(source, "fn main() -> int { return 2; }\n"); + value(httpCall(client, server, first, "studio_language_query", query)); + httpCall(client, server, first, "studio_build_start", args().put("clientRequestId", "conformance-build")); + var build = httpCompleted(client, server, first, "conformance-build"); + value(httpCall(client, server, first, "studio_headless_boot", args().put("buildId", build.path("result").path("buildId").asText()))); + for (var op : List.of("reset", "clear_input", "state", "fault")) value(httpCall(client, server, first, "studio_headless_" + op, args())); + value(httpCall(client, server, first, "studio_headless_set_input", args().set("input", mapper.createObjectNode().put("a", true)))); + value(httpCall(client, server, first, "studio_headless_advance", args().put("clientRequestId", "conformance-advance").put("frames", 5))); + var advanced = httpCompleted(client, server, first, "conformance-advance"); + assertEquals("SUCCEEDED", advanced.path("result").path("status").asText()); + var captured = httpCall(client, server, first, "studio_headless_capture", args()); value(captured); + assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(captured.path("content").get(1).path("data").asText())); + var deleted = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).DELETE() + .header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", first).build(); + assertEquals(200, client.send(deleted, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode()); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + String reconnected = connect(client, server); + assertEquals(advanced.path("operationId"), value(httpCall(client, server, reconnected, "studio_operation_get", args().put("clientRequestId", "conformance-advance"))).path("operationId")); + runtime.kind = AutomationOutcome.Kind.GUEST_FAULT; + value(httpCall(client, server, reconnected, "studio_headless_advance", args().put("clientRequestId", "guest").put("frames", 2))); + assertEquals("GUEST_FAULT", httpCompleted(client, server, reconnected, "guest").path("result").path("status").asText()); + value(httpCall(client, server, reconnected, "studio_operation_cancel", args().put("operationId", advanced.path("operationId").asText()))); + runtime.hold = true; + String pending = value(httpCall(client, server, reconnected, "studio_headless_advance", + args().put("clientRequestId", "cancel-over-http").put("frames", 50))).path("operationId").asText(); + assertTrue(value(httpCall(client, server, reconnected, "studio_operation_cancel", args().put("operationId", pending))) + .path("cancellationRequested").asBoolean()); + runtime.gate.countDown(); + assertEquals("CANCELLED", httpCompleted(client, server, reconnected, "cancel-over-http").path("state").asText()); + value(httpCall(client, server, reconnected, "studio_headless_shutdown", args())); + value(httpCall(client, server, reconnected, "studio_control_release", args())); + error("INVALID_TASK", httpCall(client, server, reconnected, "studio_operation_get", args().put("clientRequestId", "conformance-advance"))); + session.grant(false).toCompletableFuture().join(); + task = value(httpCall(client, server, reconnected, "studio_control_acquire", rootOnly())).path("taskId").asText(); + session.reclaim().toCompletableFuture().join(); + error("INVALID_TASK", httpCall(client, server, reconnected, "studio_build_start", args().put("clientRequestId", "late"))); + } finally { lsp.shutdown(project); } + } + String connect(java.net.http.HttpClient client, LocalMcpServer server) throws Exception { + 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", "conformance-test").put("version", "1"); + String connection = post(client, server, null, initialize).headers().firstValue("Mcp-Session-Id").orElseThrow(); + assertEquals(202, post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized")).statusCode()); + return connection; + } + JsonNode httpCompleted(java.net.http.HttpClient client, LocalMcpServer server, String connection, String request) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + var result = value(httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", request))); + if (result.path("workerTerminated").asBoolean()) return result; + Thread.sleep(5); + } while (System.nanoTime() < deadline); + throw new AssertionError("Operation did not terminate"); + } 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); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java new file mode 100644 index 00000000..1019562e --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java @@ -0,0 +1,21 @@ +package p.studio.api.automation; + +import p.studio.api.operation.OperationSubscription; +import java.nio.file.Path; +import java.util.Optional; + +/** Connection assistance only. Copying credentials never grants project authority. */ +public interface AgentConnectionGuide { + Optional endpoint(); + /** Explicit secret-bearing export for the clipboard; never persist or log this string. */ + String configuration(Path openProjectRoot); + OperationSubscription subscribe(Runnable changed); + + static AgentConnectionGuide unavailable() { + return new AgentConnectionGuide() { + public Optional endpoint() { return Optional.empty(); } + public String configuration(Path root) { throw new IllegalStateException("Connection unavailable"); } + public OperationSubscription subscribe(Runnable changed) { changed.run(); return () -> {}; } + }; + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java index b6926533..b208e31e 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java @@ -6,6 +6,7 @@ public enum I18n { WORKSPACE_DEV("workspace.dev"), DEV_GRANT("dev.grant"), DEV_RECLAIM("dev.reclaim"), DEV_COPY_CONFIG("dev.copyConfig"), DEV_MCP_UNAVAILABLE("dev.mcpUnavailable"), DEV_EXTERNAL_WARNING("dev.externalWarning"), + DEV_MCP_INSTRUCTIONS("dev.mcpInstructions"), DEV_CONFIG_COPIED("dev.configCopied"), DEV_CONFIG_FAILED("dev.configFailed"), DEV_MANUAL("dev.manual"), DEV_WAITING("dev.waiting"), DEV_WORKING("dev.working"), DEV_RETURNING("dev.returning"), DEV_SAVE_GRANT("dev.saveGrant"), DEV_UNSAVED("dev.unsaved"), DEV_DIAGNOSTICS("dev.diagnostics"), DEV_HISTORY("dev.history"), diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java index 9600f564..867bc98a 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java @@ -66,7 +66,7 @@ public final class MainView extends BorderPane { final AssetColorSchemaFactory assetColorSchemaFactory, final TiledAssetService tiledAssetService, final SceneBankWorkflow sceneBankWorkflow, - final ProjectActivityHistoryStore activityHistoryStore) { + final ProjectActivityHistoryStore activityHistoryStore, final p.studio.api.automation.AgentConnectionGuide connectionGuide) { initializing = true; this.eventBus = eventBus; this.projectSession = projectSession; @@ -98,7 +98,7 @@ public final class MainView extends BorderPane { host.register(new DebugWorkspace(projectReference, projectSession.executionSession(), i18n, eventBus)); final var shipperWorkspace = new ShipperWorkspace(projectReference, shipper, i18n, eventBus); host.register(shipperWorkspace); - host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus)); + host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus, connectionGuide)); documentRegistration = projectSession.automation().registerDocuments(assetWorkspace.documentHandoff()); p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(assetWorkspace.rootNode(), () -> projectSession.automation().snapshot().manualAllowed()); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java index c4e25bdc..c48966db 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java @@ -70,6 +70,7 @@ public final class StudioWindowCoordinator implements AutoCloseable { private final TiledAssetService tiledAssetService; private final SceneBankWorkflow sceneBankWorkflow; private final ProjectActivityHistoryStore activityHistoryStore; + private final p.studio.api.automation.AgentConnectionGuide connectionGuide; private final Object lifecycleMonitor = new Object(); private volatile boolean closed; private volatile ProjectSession pendingProjectSession; @@ -104,7 +105,8 @@ public final class StudioWindowCoordinator implements AutoCloseable { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { + this.connectionGuide = Objects.requireNonNull(connectionGuide); this.launcherStage = Objects.requireNonNull(launcherStage, "launcherStage"); this.projectCatalogService = Objects.requireNonNull(projectCatalogService, "projectCatalogService"); this.knownProjectsService = Objects.requireNonNull(knownProjectsService, "knownProjectsService"); @@ -263,7 +265,7 @@ public final class StudioWindowCoordinator implements AutoCloseable { executor, theme, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, - activityHistoryStore); + activityHistoryStore, connectionGuide); this.projectSession = projectSession; final Scene scene = new Scene(mainView, PROJECT_WIDTH, PROJECT_HEIGHT); scene.getStylesheets().add(theme.getDefaultTheme()); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java index 05810691..b1fe3936 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java @@ -25,13 +25,23 @@ public final class DevWorkspace extends Workspace { private final TextArea diagnostics = new TextArea(), history = new TextArea(); private final ImageView canvas = new ImageView(); private final Button grant = new Button(), reclaim = new Button(); + private final Button configuration = new Button(); + private final Label availability = new Label(), copyStatus = new Label(); + private final AgentConnectionGuide connectionGuide; + private final java.nio.file.Path projectRoot; + private OperationSubscription connectionSubscription; private OperationSubscription subscription; private long generation; private CanonicalCapture rendered; private final javafx.beans.value.ChangeListener localeListener; public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events) { + this(project, automation, i18n, events, AgentConnectionGuide.unavailable()); + } + public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events, + AgentConnectionGuide connectionGuide) { super(project, events); this.automation = automation; this.i18n = i18n; + this.connectionGuide = java.util.Objects.requireNonNull(connectionGuide); projectRoot = project.rootPath(); localeListener = (o, before, after) -> apply(this.automation.snapshot()); scroll.setFitToWidth(true); root.setPadding(new Insets(16)); root.getStyleClass().add("dev-workspace"); @@ -40,9 +50,13 @@ public final class DevWorkspace extends Workspace { reclaim.textProperty().bind(i18n.bind(I18n.DEV_RECLAIM)); grant.setOnAction(e -> grant(false)); reclaim.setOnAction(e -> automation.reclaim()); - Button configuration = new Button(); configuration.setId("dev-mcp-config"); - configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); configuration.setDisable(true); - Label availability = new Label(); availability.textProperty().bind(i18n.bind(I18n.DEV_MCP_UNAVAILABLE)); + configuration.setId("dev-mcp-config"); + configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); + configuration.setOnAction(e -> copyConfiguration()); + availability.setId("dev-mcp-endpoint"); availability.setWrapText(true); + copyStatus.setId("dev-mcp-copy-status"); + Label instructions = new Label(); instructions.setWrapText(true); + instructions.textProperty().bind(i18n.bind(I18n.DEV_MCP_INSTRUCTIONS)); Label warning = new Label(); warning.setWrapText(true); warning.textProperty().bind(i18n.bind(I18n.DEV_EXTERNAL_WARNING)); canvas.setPreserveRatio(true); canvas.setSmooth(false); canvas.setFitWidth(640); canvas.setFitHeight(360); @@ -50,7 +64,7 @@ public final class DevWorkspace extends Workspace { diagnostics.setEditable(false); diagnostics.setPrefRowCount(3); history.setEditable(false); history.setPrefRowCount(5); root.getChildren().addAll(new Label(project.name() + " — " + project.rootPath()), - state, new HBox(10, grant, reclaim, configuration), availability, warning, + state, new HBox(10, grant, reclaim, configuration), availability, copyStatus, instructions, warning, operation, imageStatus, imagePane, identity, pane(I18n.DEV_DIAGNOSTICS, diagnostics), pane(I18n.DEV_HISTORY, history)); apply(automation.snapshot()); @@ -71,11 +85,16 @@ public final class DevWorkspace extends Workspace { Runnable update = () -> { if (generation == subscribed) apply(snapshot); }; if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); }); + connectionSubscription = connectionGuide.subscribe(() -> { + Runnable update = () -> { if (generation == subscribed) { copyStatus.setText(""); updateConnection(); } }; + if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); + }); } @Override public void unLoad() { generation++; i18n.localeProperty().removeListener(localeListener); if (subscription != null) { subscription.unsubscribe(); subscription = null; } + if (connectionSubscription != null) { connectionSubscription.unsubscribe(); connectionSubscription = null; } } private void grant(boolean save) { automation.grant(save).whenComplete((result, failure) -> Platform.runLater(() -> { @@ -89,6 +108,7 @@ public final class DevWorkspace extends Workspace { })); } private void apply(AutomationSnapshot snapshot) { + updateConnection(); var view = DevWorkspaceProjection.from(snapshot); state.setText(i18n.text(switch (view.state()) { case MANUAL -> I18n.DEV_MANUAL; @@ -105,4 +125,21 @@ public final class DevWorkspace extends Workspace { canvas.setImage(rendered == null ? null : new Image(new ByteArrayInputStream(rendered.png()))); } } + private void updateConnection() { + var endpoint = connectionGuide.endpoint(); + configuration.setDisable(automation.snapshot().closed() || endpoint.isEmpty()); + availability.setText(endpoint.orElseGet(() -> i18n.text(I18n.DEV_MCP_UNAVAILABLE))); + } + private void copyConfiguration() { + try { + if (automation.snapshot().closed()) throw new IllegalStateException("Project closed"); + var content = new javafx.scene.input.ClipboardContent(); + content.putString(connectionGuide.configuration(projectRoot)); + boolean copied = javafx.scene.input.Clipboard.getSystemClipboard().setContent(content); + copyStatus.setText(i18n.text(copied ? I18n.DEV_CONFIG_COPIED : I18n.DEV_CONFIG_FAILED)); + } catch (RuntimeException unavailable) { + // Never render exception payloads or credential-bearing configuration in diagnostics. + copyStatus.setText(i18n.text(I18n.DEV_CONFIG_FAILED)); updateConnection(); + } + } } diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties index 6ee9a196..50376187 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties @@ -361,7 +361,10 @@ workspace.dev=DEV dev.grant=Grant control to AI dev.reclaim=Interrupt and reclaim control dev.copyConfig=Copy MCP configuration -dev.mcpUnavailable=MCP connection is not available yet. This stage provides project control and observation. +dev.mcpUnavailable=MCP connection is unavailable. +dev.mcpInstructions=Copy the connection descriptor into your external client's MCP setup (adapt its format if needed). Connect → read project/language references → acquire after a human grant → edit saved files and validate with LSP/build → release. Copying does not grant control. Keep the token private and out of versioned files; recopy after restarting Studio. Only listed tools are available. +dev.configCopied=Connection descriptor and project instructions copied. Contains a private token. +dev.configFailed=Could not copy the current connection configuration. dev.externalWarning=Reclaiming control stops Studio-managed work, not direct writes by your external agent. Stop that client separately. Existing edits are preserved. dev.manual=Manual control dev.waiting=Waiting for agent — project control granted diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties index ff673d74..dd23428c 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties @@ -32,7 +32,10 @@ workspace.dev=DEV dev.grant=Ceder controle à IA dev.reclaim=Interromper e retomar controle dev.copyConfig=Copiar configuração MCP -dev.mcpUnavailable=A conexão MCP ainda não está disponível. Esta etapa oferece controle do projeto e acompanhamento. +dev.mcpUnavailable=A conexão MCP está indisponível. +dev.mcpInstructions=Copie o descritor de conexão para a configuração MCP do cliente externo (adapte o formato se necessário). Conecte → consulte projeto/linguagens/referências → adquira após cessão humana → edite arquivos salvos e valide com LSP/build → devolva. Copiar não cede controle. Mantenha o token privado e fora de arquivos versionados; copie novamente após reiniciar o Studio. Somente as ferramentas listadas estão disponíveis. +dev.configCopied=Descritor de conexão e instruções do projeto copiados. Contém um token privado. +dev.configFailed=Não foi possível copiar a configuração atual de conexão. dev.externalWarning=Retomar controle encerra o trabalho gerenciado pelo Studio, não as escritas diretas do agente externo. Pare esse cliente separadamente. As alterações existentes são preservadas. dev.manual=Controle manual dev.waiting=Aguardando agente — controle do projeto cedido From bc76f08bbdeeca80c5352e9273a37f44e5e9fe39 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 11:02:21 +0100 Subject: [PATCH 08/15] implement real headless process gateway and supervision --- README.md | 11 + .../10. DEV and Automation Specification.md | 19 ++ prometeu-app/build.gradle.kts | 12 +- .../p/studio/app/runtime/HeadlessLimits.java | 20 ++ .../app/runtime/HeadlessProcessGateway.java | 41 +++ .../app/runtime/HeadlessProcessSession.java | 306 ++++++++++++++++++ .../p/studio/app/runtime/HeadlessWire.java | 103 ++++++ .../p/studio/app/mcp/McpTaskToolsTest.java | 2 +- .../p/studio/app/runtime/HeadlessFixture.java | 74 +++++ .../runtime/HeadlessInstalledRuntimeTest.java | 79 +++++ .../runtime/HeadlessProcessSessionTest.java | 97 ++++++ .../api/automation/CanonicalCapture.java | 10 +- .../studio/core/session/DefaultTaskTools.java | 2 +- 13 files changed, 771 insertions(+), 5 deletions(-) create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java diff --git a/README.md b/README.md index 65a6da41..25c0b8e3 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,17 @@ remain the developer's responsibility. See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) for schemas, authorization, limits and delivery boundaries. +The real headless process adapter can be verified independently of its pending +task-service composition, using an extracted runtime distribution: + +```bash +./gradlew :prometeu-app:headlessProcessTest -PstudioRuntimeInstall=/absolute/path/to/runtime +``` + +This gate builds an installed PBS example, launches the actual runtime, checks +canonical PNGs and explicit reset/reboot, cancels an advance and verifies process +cleanup. It does not download a runtime or substitute a protocol fixture. + ## Requirements - JDK 21 or newer recommended for local development diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md index bf1dcfef..b35972a6 100644 --- a/docs/specs/studio/10. DEV and Automation Specification.md +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -203,6 +203,14 @@ mandatory capability MUST block the session; compatible minor additions are permitted. It MUST obey complete UTF-8 JSONL framing and separate protocol stdout from stderr diagnostics. Invalid input/schema MUST not disappear silently. +The application adapter resolves the executable from `ProjectLocalStudioSetup`, +launches it without a shell in the project root, and passes all six effective +limits explicitly. Hello and initialize share one handshake deadline. Required +hello limits must match the launch configuration; request IDs and session IDs +are checked on every subsequent response. Partial lines, invalid UTF-8, +duplicate JSON keys, uncorrelated replies and non-monotonic progress invalidate +the process. Stderr is drained independently into bounded diagnostics. + The runtime-owned surface covers boot/reset, set/clear normalized input, advance, capture, state/fault, cancel and shutdown. Conflicting execution work MUST NOT execute concurrently or be silently queued. Advance MUST preserve @@ -210,6 +218,10 @@ requested/completed counts and stop reasons. Cancellation is observed between frames; the current frame retains its deterministic watchdog, not a wall-clock guest deadline. No background realtime game loop is introduced for automation. +Reset leaves the runtime unbooted and clears its capture. It does not implicitly +boot the cartridge again. A subsequent explicit boot may reuse the session's +known build cartridge; an invalidated process requires an explicit new session. + | Configurable, handshake-advertised limit | Default | | --- | --- | | Frames per advance | 600 | @@ -229,9 +241,16 @@ Screenshot means the runtime's canonical **RGBA8888 framebuffer bitmap**. Capture MUST use lossless PNG/base64 with dimensions, original stride/layout, runtime session, `logical_frame_index` and `FrameId`. These two frame identities MUST NOT be assumed numerically equal. Studio MUST attach build correlation. +Both identities retain the full unsigned 64-bit range: Java uses `BigInteger`, +and MCP serializes integer JSON values without conversion through floating point. Hashes MAY supplement but MUST NOT replace pixels. No desktop/window screenshot, temporary-image-file transport or continuous video is permitted. +The adapter validates base64, PNG signature, RGBA8 header, dimensions and decoded +image consistency in memory, then forwards the original PNG bytes unchanged. +Its decoder currently guards allocations at 16,777,216 pixels; exceeding this +bound fails explicitly rather than resizing or substituting the image. + Agent and DEV MUST receive the same capture and correlation for requested advances. DEV MUST identify images from an older build/session as stale during edits/rebuilds. The previous execution MUST stop before rebuilding artifacts diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 1e2ad67e..273cb769 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -32,7 +32,7 @@ javafx { } // Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. -tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class") } +tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class") } tasks.register("devDesktopTest") { group = "verification" description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." @@ -55,3 +55,13 @@ tasks.register("installedKnowledgeTest") { inputs.dir(distribution) systemProperty("studio.test.distribution", distribution.get().asFile.absolutePath) } + +tasks.register("headlessProcessTest") { + group = "verification" + description = "Exercises the configured packaged headless runtime (requires -PstudioRuntimeInstall)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/HeadlessInstalledRuntimeTest.class") + systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java new file mode 100644 index 00000000..8a6f077a --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java @@ -0,0 +1,20 @@ +package p.studio.app.runtime; + +import java.util.List; + +/** Configured before launch, then verified against the runtime's effective handshake. */ +public record HeadlessLimits(long maxFrames, int maxCommandBytes, int maxResponseBytes, + long handshakeTimeoutMs, long callTimeoutMs, long shutdownTimeoutMs) { + public HeadlessLimits { + if (maxFrames < 1 || maxCommandBytes < 4096 || maxResponseBytes < 4096 + || handshakeTimeoutMs < 1 || callTimeoutMs < 1 || shutdownTimeoutMs < 1) + throw new IllegalArgumentException("Invalid headless limits"); + } + public static HeadlessLimits defaults() { return new HeadlessLimits(600, 65536, 33554432, 5000, 60000, 5000); } + List arguments() { + return List.of("headless", "--stdio", "--max-frames", Long.toString(maxFrames), + "--max-command-bytes", Integer.toString(maxCommandBytes), "--max-response-bytes", Integer.toString(maxResponseBytes), + "--handshake-timeout-ms", Long.toString(handshakeTimeoutMs), "--call-timeout-ms", Long.toString(callTimeoutMs), + "--shutdown-timeout-ms", Long.toString(shutdownTimeoutMs)); + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java new file mode 100644 index 00000000..137c661f --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java @@ -0,0 +1,41 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.api.shipper.ShipperPrepareResult; +import p.studio.core.runtime.HeadlessGateway; +import java.nio.file.*; +import java.util.*; +import java.util.function.Function; + +/** Configured-installation-only headless launcher; independent of desktop Debug. */ +public final class HeadlessProcessGateway implements HeadlessGateway { + private final ObjectMapper mapper; + private final Function setup; + private final HeadlessLimits limits; + public HeadlessProcessGateway(ObjectMapper mapper, Function setup) { + this(mapper, setup, HeadlessLimits.defaults()); + } + public HeadlessProcessGateway(ObjectMapper mapper, Function setup, HeadlessLimits limits) { + 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(); + 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)) + throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Configured runtime executable is unavailable"); + if (!build.success() || build.manifestPath() == null || !Files.isRegularFile(build.manifestPath())) + throw new AutomationException(AutomationFailure.Code.BUILD_NOT_FOUND, "Successful build manifest is unavailable"); + Path root = project.rootPath().toRealPath(), manifest = build.manifestPath().toRealPath(); + if (!manifest.startsWith(root)) throw new AutomationException(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Build manifest is outside the project"); + var command = new ArrayList(); command.add(executable.toString()); command.addAll(limits.arguments()); + final Process process; + 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; } + catch (Exception failure) { session.abort("Headless startup failed"); throw failure; } + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java new file mode 100644 index 00000000..ded75db0 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java @@ -0,0 +1,306 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.databind.*; +import p.studio.api.automation.*; +import p.studio.core.runtime.HeadlessGateway; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; +import static p.studio.app.runtime.HeadlessWire.*; + +/** One supervised process, bounded JSONL, no retry/replay and no simulated-time clock. */ +final class HeadlessProcessSession implements HeadlessGateway.Session { + private final Process process; + private final ObjectMapper mapper; + private final HeadlessLimits limits; + private final String buildId; + private volatile String sessionId; + private volatile JsonNode hello; + private Path cartridge; + private final CompletableFuture greeting = new CompletableFuture<>(); + private final Map pending = new ConcurrentHashMap<>(); + private final Set descendants = ConcurrentHashMap.newKeySet(); + private final ExecutorService io = Executors.newVirtualThreadPerTaskExecutor(); + private final ExecutorService writer = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("headless-writer").factory()); + private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("headless-supervisor").factory()); + private final ReentrantLock work = new ReentrantLock(); + private final AtomicBoolean dead = new AtomicBoolean(); + private final AtomicReference advance = new AtomicReference<>(); + private final Deque stderr = new ArrayDeque<>(); + private volatile boolean closing; + private CompletableFuture shutdown; + + HeadlessProcessSession(Process process, ObjectMapper source, HeadlessLimits limits, String buildId) { + this.process = process; this.limits = limits; this.buildId = buildId; + mapper = source.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + mapper.getFactory().setStreamReadConstraints(StreamReadConstraints.builder().maxStringLength(limits.maxResponseBytes()).build()); + timer.scheduleAtFixedRate(() -> { if (process.isAlive()) process.descendants().forEach(descendants::add); }, 0, 20, TimeUnit.MILLISECONDS); + io.execute(this::readOutput); io.execute(this::readErrors); + process.onExit().thenRun(() -> { if (!closing) abort("Headless process exited"); }); + } + + void initializeAndBoot(Path cartridge) throws Exception { + this.cartridge = cartridge; + 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 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 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())); + } + @Override public String sessionId() { return sessionId; } + @Override public long maxFramesPerAdvance() { return limits.maxFrames(); } + long pid() { return process.pid(); } + boolean alive() { return process.isAlive() || descendants.stream().anyMatch(ProcessHandle::isAlive); } + + @Override public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map input) throws Exception { + if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active"); + try { + 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"; + 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()); + var values = new LinkedHashMap(); values.put("sessionId", sessionId); values.put("buildId", buildId); + CanonicalCapture capture = null; + switch (action) { + case CAPTURE -> capture = capture(result, sessionId, buildId); + case STATE, RESET, BOOT -> { + state(result); values.put("state", mapper.convertValue(result, Object.class)); + 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)); + } + case FAULT -> { fault(result); values.put("fault", mapper.convertValue(result, Object.class)); } + default -> { if (!result.isObject()) throw invalid("Invalid acknowledgement"); } + } + return new TaskTools.HeadlessReply(values, capture); + } catch (AutomationException failure) { invalidateMalformed(failure); throw failure; } + finally { work.unlock(); } + } + + @Override public AutomationOutcome advance(long frames, Consumer progress) throws Exception { + if (frames < 0 || frames > limits.maxFrames()) throw new AutomationException(AutomationFailure.Code.LIMIT_EXCEEDED, "Requested frames exceed effective limit"); + if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active"); + boolean interrupted = false; + try { + var item = new Pending("advance", frames, progress); advance.set(item); + send(item, mapper.createObjectNode().put("frames", frames)); + JsonNode result; + try { result = await(item.result, limits.callTimeoutMs()); } + catch (InterruptedException cancelled) { + interrupted = true; cancel(); + result = awaitUninterruptibly(item.result, limits.shutdownTimeoutMs()); + } catch (TimeoutException timedOut) { + cancel(); + try { awaitUninterruptibly(item.result, limits.shutdownTimeoutMs()); } catch (Exception ignored) { } + abort("Headless advance deadline exceeded"); throw infrastructure("Headless advance deadline exceeded"); + } + long requested = count(result, "requested"), completed = count(result, "completed"); + if (requested != frames || completed > frames || completed < item.completed) throw invalid("Inconsistent final progress"); + progress.accept(new TrackedOperation.Progress(frames, completed)); + var diagnostics = new ArrayList(); + var kind = switch (text(result, "stop")) { + 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 "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"); + }; + CanonicalCapture captured = null; + if (!closing) { + try { captured = capture(request("capture", mapper.createObjectNode(), null, limits.callTimeoutMs()), sessionId, buildId); } + catch (AutomationException noFrame) { if (noFrame.failure().code() != AutomationFailure.Code.NO_FRAME_AVAILABLE) throw noFrame; } + } + synchronized (stderr) { diagnostics.addAll(stderr); stderr.clear(); } + return new AutomationOutcome(kind, requested, completed, diagnostics, captured); + } catch (TimeoutException timeout) { abort("Cancellation deadline exceeded"); throw infrastructure("Cancellation deadline exceeded"); } + catch (AutomationException failure) { invalidateMalformed(failure); throw failure; } + finally { advance.set(null); work.unlock(); if (interrupted) Thread.currentThread().interrupt(); } + } + + @Override public void cancel() { + var target = advance.get(); + if (target == null || target.result.isDone() || !target.cancelled.compareAndSet(false, true) || dead.get()) return; + var cancel = new Pending("cancel", null, null); + send(cancel, mapper.createObjectNode().put("targetRequestId", target.id)); + timer.schedule(() -> { if (!target.result.isDone() || !cancel.result.isDone()) abort("Runtime did not stop after cancellation"); }, limits.shutdownTimeoutMs(), TimeUnit.MILLISECONDS); + } + @Override public synchronized CompletionStage shutdown() { + if (shutdown != null) return shutdown; + closing = true; + shutdown = CompletableFuture.runAsync(() -> { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.shutdownTimeoutMs()); + try { + if (!dead.get()) { + var response = request("shutdown", mapper.createObjectNode(), null, remaining(deadline)); + if (!response.path("closed").isBoolean() || !response.path("closed").booleanValue()) throw invalid("Missing shutdown acknowledgement"); + if (!process.waitFor(remaining(deadline), TimeUnit.MILLISECONDS)) throw new TimeoutException(); + } + } 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"); } + }); + return shutdown; + } + private JsonNode request(String command, JsonNode params, Consumer observer, long timeout) throws Exception { + var item = new Pending(command, null, observer); send(item, params); + try { return await(item.result, timeout); } + catch (InterruptedException interrupted) { abort("Headless request interrupted"); Thread.currentThread().interrupt(); throw infrastructure("Headless request interrupted"); } + catch (TimeoutException exceeded) { + if (!command.equals("shutdown") && !command.equals("initialize") && !dead.get()) { + closing = true; + try { + var stop = new Pending("shutdown", null, null); send(stop, mapper.createObjectNode()); + awaitUninterruptibly(stop.result, limits.shutdownTimeoutMs()); + } catch (Exception ignored) { /* Deadline escalation below always invalidates this process. */ } + } + abort("Headless request deadline exceeded"); throw infrastructure("Headless request deadline exceeded"); + } + } + private void send(Pending item, JsonNode params) { + if (dead.get()) throw infrastructure("Headless session lost; create a new session explicitly"); + var envelope = mapper.createObjectNode().put("requestId", item.id).put("command", item.command); envelope.set("params", params); + final byte[] bytes; + try { bytes = mapper.writeValueAsBytes(envelope); } catch (IOException invalid) { throw new IllegalArgumentException(invalid); } + if (bytes.length > limits.maxCommandBytes()) throw new AutomationException(AutomationFailure.Code.LIMIT_EXCEEDED, "Command exceeds runtime message limit"); + item.params = params; pending.put(item.id, item); + try { writer.execute(() -> { + try { process.getOutputStream().write(bytes); process.getOutputStream().write('\n'); process.getOutputStream().flush(); } + catch (IOException failed) { abort("Headless stdin closed"); } + }); } catch (RejectedExecutionException closed) { abort("Headless writer closed"); throw infrastructure("Headless writer closed"); } + } + + private void readOutput() { + try (var input = new BufferedInputStream(process.getInputStream())) { + var bytes = new ByteArrayOutputStream(); int next; + while ((next = input.read()) != -1) { + if (next == '\n') { + byte[] line = bytes.toByteArray(); bytes.reset(); + String json = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(line)).toString(); + receive(mapper.readTree(json)); + } else { + if (bytes.size() >= limits.maxResponseBytes()) throw invalid("Response exceeds limit"); + bytes.write(next); + } + } + if (bytes.size() != 0) throw invalid("Truncated JSONL response"); + if (!closing || !pending.isEmpty()) abort("Headless stdout closed"); + } catch (Exception failure) { abort("Malformed or lost headless output"); } + } + private void receive(JsonNode message) { + process.descendants().forEach(descendants::add); + if (message == null || !message.isObject()) throw invalid("Expected object"); + if (sessionId == null) { + if (!text(message, "type").equals("hello")) throw invalid("Expected hello"); + sessionId = text(message, "sessionId"); greeting.complete(message); return; + } + if (!text(message, "sessionId").equals(sessionId)) throw invalid("Wrong session identity"); + var item = pending.get(text(message, "requestId")); + if (item == null) throw invalid("Uncorrelated response"); + if (text(message, "type").equals("progress")) { + long requested = count(message, "requested"), completed = count(message, "completed"); + if (item.frames == null || requested != item.frames || completed < item.completed || completed > requested) throw invalid("Invalid progress"); + item.completed = completed; item.observer.accept(new TrackedOperation.Progress(requested, completed)); return; + } + if (!text(message, "type").equals("response") || message.has("result") == message.has("error")) throw invalid("Invalid response envelope"); + if (message.has("error")) { + var error = message.path("error"); error(error); + var code = switch (text(error, "code")) { + case "no_frame_available" -> AutomationFailure.Code.NO_FRAME_AVAILABLE; + case "busy", "already_booted" -> AutomationFailure.Code.BUSY; + 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; + default -> AutomationFailure.Code.INFRASTRUCTURE_FAILURE; + }; + pending.remove(item.id); + item.result.completeExceptionally(new AutomationException(code, "Runtime " + error.path("code").asText() + ": " + error.path("message").asText())); + } else { + var result = message.get("result"); + if (item.command.equals("cancel") && (!result.path("requested").isBoolean() || !result.path("requested").booleanValue() + || !result.path("targetRequestId").equals(item.params.path("targetRequestId")))) throw invalid("Invalid cancellation acknowledgement"); + pending.remove(item.id); item.result.complete(result); + } + } + private void readErrors() { + try (var input = process.getErrorStream()) { + byte[] bytes = new byte[1024]; int read; + while ((read = input.read(bytes)) != -1) synchronized (stderr) { + stderr.addLast(new String(bytes, 0, read, StandardCharsets.UTF_8)); + while (stderr.size() > 32) stderr.removeFirst(); + } + } catch (IOException ignored) { } + } + void abort(String message) { + if (dead.compareAndSet(false, true)) { + terminate(); + greeting.completeExceptionally(infrastructure(message)); + pending.values().forEach(item -> item.result.completeExceptionally(infrastructure(message))); pending.clear(); + } else terminate(); + } + private void terminate() { + dead.set(true); + process.descendants().forEach(descendants::add); + descendants.forEach(ProcessHandle::destroyForcibly); process.destroyForcibly(); + writer.shutdownNow(); timer.shutdownNow(); io.shutdown(); + // Killing first unblocks pipe IO; closing a writer before kill can wait on its blocked monitor. + try { process.waitFor(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); } + descendants.forEach(handle -> { if (handle.isAlive()) handle.destroyForcibly(); }); + for (var handle : descendants) { + try { handle.onExit().get(1000, TimeUnit.MILLISECONDS); } + catch (Exception ignored) { /* A failed cleanup is surfaced by shutdown below. */ } + } + if (!process.isAlive()) { + try { process.getOutputStream().close(); } catch (IOException ignored) { } + } + } + private void invalidateMalformed(AutomationException failure) { + if (failure.getMessage().startsWith("Invalid headless response:")) abort("Invalid headless response"); + } + private static AutomationException infrastructure(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, message); } + private static T await(CompletableFuture future, long timeout) throws Exception { + try { return future.get(timeout, TimeUnit.MILLISECONDS); } + catch (ExecutionException error) { if (error.getCause() instanceof Exception cause) throw cause; throw error; } + } + private static long remaining(long deadline) throws TimeoutException { + long nanos = deadline - System.nanoTime(); + if (nanos <= 0) throw new TimeoutException(); + return Math.max(1, TimeUnit.NANOSECONDS.toMillis(nanos)); + } + private static T awaitUninterruptibly(CompletableFuture future, long timeout) throws Exception { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); + while (true) { + try { return await(future, Math.max(1, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()))); } + catch (InterruptedException ignored) { if (System.nanoTime() >= deadline) throw new TimeoutException(); } + } + } + private static final class Pending { + final String id = UUID.randomUUID().toString(), command; + final Long frames; + final Consumer observer; + final CompletableFuture result = new CompletableFuture<>(); + final AtomicBoolean cancelled = new AtomicBoolean(); + volatile long completed; + JsonNode params; + Pending(String command, Long frames, Consumer observer) { this.command = command; this.frames = frames; this.observer = observer; } + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java new file mode 100644 index 00000000..1e7ae406 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java @@ -0,0 +1,103 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.JsonNode; +import p.studio.api.automation.*; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.*; + +/** Validates required v1 fields while permitting compatible minor additions. */ +final class HeadlessWire { + static final Set CAPABILITIES = Set.of("boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "cancel", "shutdown"); + static String text(JsonNode node, String key) { + var value = node.path(key); + if (!value.isTextual() || value.textValue().isBlank()) throw invalid("Missing " + key); + return value.textValue(); + } + static BigInteger uint(JsonNode value) { + if (!value.isIntegralNumber() || value.bigIntegerValue().signum() < 0 || value.bigIntegerValue().bitLength() > 64) throw invalid("Invalid uint64"); + return value.bigIntegerValue(); + } + static long count(JsonNode node, String key) { + try { return uint(node.path(key)).longValueExact(); } + catch (ArithmeticException overflow) { throw invalid("Counter exceeds requested operation range"); } + } + static void version(JsonNode value) { + if (!value.path("major").isIntegralNumber() || !value.path("major").bigIntegerValue().equals(BigInteger.ONE)) + throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Unsupported headless protocol major"); + uint(value.path("minor")); + } + static void capabilities(JsonNode value) { + if (!value.isArray()) throw invalid("Missing capabilities"); + var actual = new HashSet(); + for (var item : value) { if (!item.isTextual()) throw invalid("Invalid capability"); actual.add(item.textValue()); } + if (!actual.containsAll(CAPABILITIES)) throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Required headless capability unavailable"); + } + static void state(JsonNode value) { + for (var key : List.of("pc", "logicalFrameIndex", "tickIndex", "appId")) uint(value.path(key)); + if (!Set.of("running", "paused", "terminated", "faulted").contains(text(value, "status")) || !value.path("stackTop").isArray()) throw invalid("Invalid state"); + for (var item : value.path("stackTop")) { + var data = item.path("value"); + boolean valid = switch (text(item, "kind")) { + case "int32" -> data.isIntegralNumber() && data.canConvertToInt(); + case "int64" -> data.isTextual() && signed64(data.textValue()); + case "float64", "string" -> data.isTextual(); + case "boolean" -> data.isBoolean(); + case "null" -> data.isNull(); + case "heap_ref" -> { uint(data); yield true; } + default -> false; + }; + if (!valid) throw invalid("Invalid typed stack value"); + } + } + private static boolean signed64(String text) { try { Long.parseLong(text); return true; } catch (NumberFormatException invalid) { return false; } } + static void error(JsonNode value) { + text(value, "code"); + if (!value.path("message").isTextual() || !value.path("details").isObject()) throw invalid("Invalid structured error"); + } + static void fault(JsonNode value) { + if (value.isNull()) return; + if (!value.path("pc").isNull()) uint(value.path("pc")); + if (!value.path("summary").isTextual()) throw invalid("Invalid fault summary"); + switch (text(value, "kind")) { + case "vm_trap" -> { + var trap = value.path("trap"); + for (var key : List.of("pc", "code", "opcode")) uint(trap.path(key)); + if (!trap.path("message").isTextual() || !(trap.path("span").isObject() || trap.path("span").isNull())) throw invalid("Invalid trap"); + } + case "vm_panic" -> { if (!value.path("message").isTextual()) throw invalid("Invalid panic"); } + case "vm_init" -> { text(value.path("initError"), "code"); text(value.path("initError"), "message"); } + default -> throw invalid("Invalid fault kind"); + } + } + static CanonicalCapture capture(JsonNode value, String session, String build) { + if (!text(value, "mimeType").equals("image/png") || !text(value, "encoding").equals("base64") || !text(value, "pixelFormat").equals("RGBA8888")) throw invalid("Invalid capture encoding"); + int width = dimension(value, "width"), height = dimension(value, "height"), stride = dimension(value, "stridePixels"); + if (stride < width || (long) width * height > 16_777_216) throw invalid("Invalid or oversized framebuffer layout"); + final byte[] png; + try { png = Base64.getDecoder().decode(text(value, "data")); } + catch (IllegalArgumentException malformed) { throw invalid("Invalid capture base64"); } + byte[] signature = {(byte)137,80,78,71,13,10,26,10}; + if (png.length < 33 || !Arrays.equals(signature, Arrays.copyOf(png, 8))) throw invalid("Invalid PNG"); + var header = ByteBuffer.wrap(png); + if (header.getInt(8) != 13 || header.getInt(12) != 0x49484452 || header.getInt(16) != width || header.getInt(20) != height + || png[24] != 8 || png[25] != 6) throw invalid("PNG does not match RGBA8888 metadata"); + try (var encoded = new javax.imageio.stream.MemoryCacheImageInputStream(new java.io.ByteArrayInputStream(png))) { + var readers = javax.imageio.ImageIO.getImageReaders(encoded); + if (!readers.hasNext()) throw invalid("Undecodable PNG"); + var reader = readers.next(); + try { + reader.setInput(encoded); + var decoded = reader.read(0); + if (decoded == null || decoded.getWidth() != width || decoded.getHeight() != height) throw invalid("Undecodable PNG"); + } finally { reader.dispose(); } + } catch (java.io.IOException malformed) { throw invalid("Undecodable PNG"); } + return new CanonicalCapture(session, build, uint(value.path("logicalFrameIndex")), uint(value.path("frameId")), width, height, stride, png); + } + private static int dimension(JsonNode value, String key) { + long number = count(value, key); + if (number < 1 || number > Integer.MAX_VALUE) throw invalid("Invalid dimension"); + return (int) number; + } + static AutomationException invalid(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Invalid headless response: " + message); } +} 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 index bebead92..d3b775ba 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -198,7 +198,7 @@ class McpTaskToolsTest { 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(java.math.BigInteger.valueOf(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()); } diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java new file mode 100644 index 00000000..56850efb --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java @@ -0,0 +1,74 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.*; +import java.io.*; +import java.math.BigInteger; +import java.nio.file.*; +import java.util.*; + +/** Deliberately adversarial child process. Never packaged into production. */ +public final class HeadlessFixture { + static final ObjectMapper MAPPER = new ObjectMapper(); + static String mode; + static void emit(JsonNode value) throws Exception { + byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8); + for (int at = 0; at < bytes.length; at += 7) { System.out.write(bytes, at, Math.min(7, bytes.length - at)); System.out.flush(); } + } + static JsonNode state() { return MAPPER.createObjectNode().put("pc", 0).put("logicalFrameIndex", new BigInteger("18446744073709551615")) + .put("tickIndex", new BigInteger("18446744073709551615")).put("appId", 1).put("status", "paused").set("stackTop", MAPPER.createArrayNode()); } + static void response(String id, JsonNode result) throws Exception { + emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", mode.equals("wrong-session") ? "alien" : "fixture").put("requestId", id).set("result", result)); + } + public static void main(String[] args) throws Exception { + mode = args[0]; + if (mode.equals("child") || mode.equals("no-hello")) { Thread.sleep(60000); return; } + if (mode.equals("malformed")) { System.out.println("not json"); Thread.sleep(60000); return; } + if (mode.equals("oversized")) { System.out.print("x".repeat(5000)); System.out.flush(); Thread.sleep(60000); return; } + 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)); + hello.set("limits", MAPPER.valueToTree(new HeadlessLimits(600, 4096, 4096, 1000, 500, 150))); + if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900); + emit(hello); + if (mode.equals("descendant")) { + var child = new ProcessBuilder(java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), "child").start(); + Files.writeString(Path.of("descendant.pid"), Long.toString(child.pid())); + } + System.err.println("fixture stderr is not JSONL"); + String active = null; long frames = 0; + 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(); + switch (command) { + case "initialize" -> response(id, MAPPER.createObjectNode().setAll(Map.of("protocolVersion", hello.path("protocolVersion"), "capabilities", hello.path("capabilities")))); + case "boot", "reset" -> response(id, state()); + case "get_state" -> { if (!mode.equals("hang-call")) response(id, state()); } + case "get_fault" -> response(id, MAPPER.nullNode()); + 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")); + } + case "cancel" -> { + if (mode.equals("hang-cancel") || mode.equals("descendant")) continue; + response(id, MAPPER.createObjectNode().put("requested", true).put("targetRequestId", active)); + response(active, MAPPER.createObjectNode().put("requested", frames).put("completed", 2).put("stop", "canceled")); + } + case "capture" -> { + var image = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB); + image.setRGB(0, 0, 0xff123456); var bytes = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(image, "png", bytes); + response(id, MAPPER.createObjectNode().put("mimeType", "image/png").put("encoding", "base64").put("pixelFormat", "RGBA8888") + .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; } + default -> response(id, MAPPER.createObjectNode()); + } + } + } + static String java() { return Path.of(System.getProperty("java.home"), "bin", "java").toString(); } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java new file mode 100644 index 00000000..4810539f --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java @@ -0,0 +1,79 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +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.app.compiler.CompilerBuildGatewayAdapter; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.core.project.*; +import p.studio.core.shipper.StudioShipperService; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Explicit packaged-process gate, not satisfied by protocol fixtures. */ +class HeadlessInstalledRuntimeTest { + @TempDir Path root; + @Test void configuredDistributionBootsSavedBuildAndReturnsDeterministicCanonicalPixels() throws Exception { + String install = System.getProperty("studio.test.runtimeInstall"); + assertNotNull(install, "Supply -PstudioRuntimeInstall="); + assertTrue(Files.isRegularFile(Path.of(install, "prometeu-headless"))); + var mapper = new ObjectMapper(); + for (var doc : p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game)) + if (doc.id().startsWith("pbs:example:game:1:")) { + Path file = root.resolve(doc.id().substring("pbs:example:game:1:".length())); + Files.createDirectories(file.getParent()); Files.writeString(file, doc.text()); + } + var setup = new ProjectLocalStudioSetupStore(mapper); + var project = new ProjectCatalogService(root, mapper, setup).openProject(root); + setup.save(project, new ProjectLocalStudioSetup(install, null)); + try (var workers = Executors.newSingleThreadExecutor(); var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) { + var build = new StudioShipperService(new CompilerBuildGatewayAdapter(), packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers)) + .prepare(project, ignored -> {}).completion().toCompletableFuture().get(15, TimeUnit.SECONDS); + assertTrue(build.success(), build.diagnostics().toString()); + var gateway = new HeadlessProcessGateway(mapper, setup::load); + var session = (HeadlessProcessSession) gateway.boot(project, "real-build", build); + try { + assertEquals(600, session.maxFramesPerAdvance()); + assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class, + () -> session.call(TaskTools.HeadlessAction.CAPTURE, Map.of())).failure().code()); + var observed = new ArrayList(); + var outcome = session.advance(3, observed::add); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, outcome.kind()); assertEquals(3, outcome.completedFrames()); + assertNotNull(outcome.capture()); assertEquals("real-build", outcome.capture().buildId()); + assertEquals(session.sessionId(), outcome.capture().sessionId()); + var image = javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(outcome.capture().png())); + assertEquals(outcome.capture().width(), image.getWidth()); assertEquals(outcome.capture().height(), image.getHeight()); + assertEquals(3L, observed.getLast().completedFrames()); + var state = session.call(TaskTools.HeadlessAction.STATE, Map.of()); + assertEquals("0.1.0", state.values().get("runtimeVersion")); + assertNull(session.call(TaskTools.HeadlessAction.FAULT, Map.of()).values().get("fault")); + session.call(TaskTools.HeadlessAction.SET_INPUT, Map.of("a", true)); + session.call(TaskTools.HeadlessAction.CLEAR_INPUT, Map.of()); + session.call(TaskTools.HeadlessAction.RESET, Map.of()); + assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class, + () -> session.call(TaskTools.HeadlessAction.CAPTURE, Map.of())).failure().code()); + session.call(TaskTools.HeadlessAction.BOOT, Map.of()); + var repeated = session.advance(3, ignored -> {}); + assertArrayEquals(outcome.capture().png(), repeated.capture().png()); + assertEquals(0, session.advance(0, ignored -> {}).completedFrames()); + assertEquals(AutomationFailure.Code.LIMIT_EXCEEDED, assertThrows(AutomationException.class, + () -> session.advance(601, ignored -> {})).failure().code()); + } finally { session.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS); } + assertFalse(session.alive()); + var cancellable = (HeadlessProcessSession) new HeadlessProcessGateway(mapper, setup::load, + new HeadlessLimits(20000, 65536, 33554432, 5000, 60000, 5000)).boot(project, "cancel-build", build); + try { + assertEquals(20000, cancellable.maxFramesPerAdvance()); + var cancelled = cancellable.advance(20000, progress -> { if (progress.completedFrames() == 1) cancellable.cancel(); }); + assertEquals(AutomationOutcome.Kind.CANCELLED, cancelled.kind()); + assertTrue(cancelled.completedFrames() >= 1 && cancelled.completedFrames() < 20000); + assertNotNull(cancelled.capture()); + } finally { cancellable.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS); } + assertFalse(cancellable.alive()); + } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java new file mode 100644 index 00000000..9fce1164 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java @@ -0,0 +1,97 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.*; + +class HeadlessProcessSessionTest { + @TempDir Path root; + static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 1000, 500, 150); + final List sessions = new ArrayList<>(); + HeadlessProcessSession start(String mode) throws Exception { + var process = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), mode).directory(root.toFile()).start(); + var session = new HeadlessProcessSession(process, new ObjectMapper(), LIMITS, "build"); sessions.add(session); return session; + } + @AfterEach void cleanup() { sessions.forEach(session -> session.abort("test cleanup")); } + @Test void fragmentedProtocolPreservesUnsignedFrameIdentityLayoutAndSeparateStderr() throws Exception { + var session = start("normal"); session.initializeAndBoot(root); + var outcome = session.advance(3, ignored -> {}); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, outcome.kind()); + assertEquals("18446744073709551615", outcome.capture().logicalFrameIndex().toString()); + assertEquals("9223372036854775808", outcome.capture().frameId().toString()); + assertEquals(3, outcome.capture().stridePixels()); + assertTrue(outcome.diagnostics().stream().anyMatch(s -> s.contains("fixture stderr"))); + var wire = p.studio.app.mcp.McpToolResult.capture(new ObjectMapper(), outcome.capture(), false).wire(); + assertEquals(outcome.capture().frameId(), wire.path("structuredContent").path("value").path("frameId").bigIntegerValue()); + session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.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); + assertThrows(Exception.class, () -> session.initializeAndBoot(root), mode); + session.abort("startup rejection"); assertFalse(session.alive(), mode); + } + } + @Test void crashRetainsOnlyObservedProgressAndNeverRestartsOrReplays() throws Exception { + var session = start("crash"); session.initializeAndBoot(root); + var known = new AtomicReference(); + assertThrows(AutomationException.class, () -> session.advance(30, known::set)); + assertEquals(2L, known.get().completedFrames()); assertFalse(session.alive()); + assertThrows(AutomationException.class, () -> session.call(TaskTools.HeadlessAction.STATE, Map.of())); + } + @Test void deadlinesStopHungCallsAndCancellationPreservesKnownPartialProgress() throws Exception { + var call = start("hang-call"); call.initializeAndBoot(root); + assertThrows(AutomationException.class, () -> call.call(TaskTools.HeadlessAction.STATE, Map.of())); assertFalse(call.alive()); + var session = start("hang-cancel"); session.initializeAndBoot(root); + var known = new AtomicReference(); + assertThrows(AutomationException.class, () -> session.advance(30, known::set)); + assertEquals(2L, known.get().completedFrames()); assertFalse(session.alive()); + } + @Test void cooperativeCancelReturnsFinalImageAndRejectsConcurrentWork() throws Exception { + var session = start("cooperative"); session.initializeAndBoot(root); + var entered = new CountDownLatch(1); + try (var workers = Executors.newSingleThreadExecutor()) { + var result = workers.submit(() -> session.advance(30, ignored -> entered.countDown())); + assertTrue(entered.await(2, TimeUnit.SECONDS)); + assertEquals(AutomationFailure.Code.BUSY, assertThrows(AutomationException.class, + () -> session.call(TaskTools.HeadlessAction.STATE, Map.of())).failure().code()); + session.cancel(); + var outcome = result.get(2, TimeUnit.SECONDS); + assertEquals(AutomationOutcome.Kind.CANCELLED, outcome.kind()); assertEquals(2, outcome.completedFrames()); assertNotNull(outcome.capture()); + } + session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.alive()); + } + @Test void malformedProgressAndCaptureInvalidateSession() throws Exception { + for (var mode : List.of("bad-progress", "bad-png")) { + var session = start(mode); session.initializeAndBoot(root); + assertThrows(AutomationException.class, () -> session.advance(3, ignored -> {})); assertFalse(session.alive()); + } + } + @Test void shutdownEscalatesAndKillsOwnedDescendantsWithoutTouchingUnrelatedProcesses() throws Exception { + var unrelated = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), "child").start(); + try { + var session = start("descendant"); session.initializeAndBoot(root); + long child = Long.parseLong(Files.readString(root.resolve("descendant.pid"))); + assertTrue(ProcessHandle.of(child).orElseThrow().isAlive()); + assertThrows(ExecutionException.class, () -> session.shutdown().toCompletableFuture().get(4, TimeUnit.SECONDS)); + assertFalse(session.alive()); assertFalse(ProcessHandle.of(child).map(ProcessHandle::isAlive).orElse(false)); + assertTrue(unrelated.isAlive()); + } finally { unrelated.destroyForcibly(); unrelated.waitFor(2, TimeUnit.SECONDS); } + } + @Test void missingConfiguredInstallationIsExplicitAndNeverDiscoversAnotherRuntime() throws Exception { + var project = new p.studio.api.project.ProjectReference("game", "1", "pbs", 1, p.studio.api.project.ProjectTarget.Game, root); + var build = p.studio.api.shipper.ShipperPrepareResult.failed(List.of(), List.of()); + var missing = new HeadlessProcessGateway(new ObjectMapper(), ignored -> p.studio.api.project.ProjectLocalStudioSetup.defaults()); + assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class, + () -> missing.boot(project, "build", build)).failure().code()); + var unavailable = new HeadlessProcessGateway(new ObjectMapper(), ignored -> new p.studio.api.project.ProjectLocalStudioSetup(root.toString(), null)); + assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class, + () -> unavailable.boot(project, "build", build)).failure().code()); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java index 582bdf0c..8d88ebee 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java @@ -1,10 +1,16 @@ package p.studio.api.automation; import java.util.Objects; /** Lossless PNG bytes; stride describes the original RGBA8888 buffer, not PNG padding. */ -public record CanonicalCapture(String sessionId, String buildId, long logicalFrameIndex, - long frameId, int width, int height, int stridePixels, byte[] png) { +public record CanonicalCapture(String sessionId, String buildId, java.math.BigInteger logicalFrameIndex, + java.math.BigInteger frameId, int width, int height, int stridePixels, byte[] png) { + public CanonicalCapture(String sessionId, String buildId, long logicalFrameIndex, long frameId, + int width, int height, int stridePixels, byte[] png) { + this(sessionId, buildId, java.math.BigInteger.valueOf(logicalFrameIndex), java.math.BigInteger.valueOf(frameId), width, height, stridePixels, png); + } public CanonicalCapture { Objects.requireNonNull(sessionId); Objects.requireNonNull(buildId); Objects.requireNonNull(png); + if (logicalFrameIndex.signum() < 0 || logicalFrameIndex.bitLength() > 64 || frameId.signum() < 0 || frameId.bitLength() > 64) + throw new IllegalArgumentException("Frame identity must be uint64"); if (width <= 0 || height <= 0 || stridePixels < width) throw new IllegalArgumentException("invalid frame layout"); png = png.clone(); } 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 index 9ed4d4bf..8a36632e 100644 --- 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 @@ -201,7 +201,7 @@ public final class DefaultTaskTools implements TaskTools { 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()); + || !captured.logicalFrameIndex().equals(current.capture().logicalFrameIndex()) || !captured.frameId().equals(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); From 379420e7a9ae891b44a8df77be89dfbe3cf2ea4f Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 11:27:42 +0100 Subject: [PATCH 09/15] compose real headless runtime with task build and lifecycle --- README.md | 14 +- ...CP Tools and Project Knowledge Contract.md | 24 ++- prometeu-app/build.gradle.kts | 3 +- .../app/StudioApplicationConfiguration.java | 5 + .../StudioApplicationConfigurationTest.java | 5 +- .../p/studio/app/mcp/McpTaskToolsTest.java | 38 +++- .../p/studio/app/runtime/HeadlessFixture.java | 4 +- .../runtime/HeadlessProcessSessionTest.java | 2 +- .../runtime/HeadlessTaskIntegrationTest.java | 176 ++++++++++++++++++ .../studio/core/session/DefaultTaskTools.java | 28 ++- 10 files changed, 272 insertions(+), 27 deletions(-) create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java diff --git a/README.md b/README.md index 25c0b8e3..8679dd72 100644 --- a/README.md +++ b/README.md @@ -53,8 +53,9 @@ authorize edits or start a task. and stop the external client separately: Studio cannot prevent its direct file writes. The current production tools cover context, references, task control, LSP, -build/pack and operation lookup/cancellation. Headless tool handlers are tested, -but remain undiscoverable until the real runtime gateway is composed. DEV is an +build/pack, operation lookup/cancellation and headless execution (17 tools). +Headless requires a runtime installation configured for the project; missing or +incompatible installations fail explicitly. DEV is an observation panel, not manual Play/input for the agent's session; **Debug** retains the human testing workflow. Edits are preserved on cancellation; Git/review/recovery remain the developer's responsibility. @@ -62,8 +63,8 @@ remain the developer's responsibility. See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) for schemas, authorization, limits and delivery boundaries. -The real headless process adapter can be verified independently of its pending -task-service composition, using an extracted runtime distribution: +The real headless process adapter and task-service composition can be verified +using an extracted runtime distribution: ```bash ./gradlew :prometeu-app:headlessProcessTest -PstudioRuntimeInstall=/absolute/path/to/runtime @@ -71,7 +72,10 @@ task-service composition, using an extracted runtime distribution: This gate builds an installed PBS example, launches the actual runtime, checks canonical PNGs and explicit reset/reboot, cancels an advance and verifies process -cleanup. It does not download a runtime or substitute a protocol fixture. +cleanup. It also runs the actual app composition through saved-file LSP queries, +rebuilds and corrective loops after compile errors and guest faults. It does not +download a runtime or substitute a protocol fixture. Full HTTP/visual integration +and external-agent acceptance remain subsequent integration gates. ## Requirements 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 5758e392..65ba939c 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 @@ -293,6 +293,15 @@ from that session and are enforced without clamping. Shutdown detaches only afte 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. +Reset leaves the attached process unbooted, marks the previous capture stale and +retains its build association. A subsequent explicit `studio_headless_boot` with +that same current buildId reboots the known cartridge within the session. Boot +without reset while a runtime is attached is rejected as busy. Reset does not +change task authority or implicitly start execution. Rebuilding ends and detaches +that process, invalidates previous buildIds and requires a fresh explicit boot. +Synchronous headless failures finish their worker before returning the error, +so a corrective call cannot race the failed worker's admission lock. + 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 @@ -429,14 +438,17 @@ authentication, Origin, endpoint/method/version handling, tool dispatch, malform 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`, 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. +The production registry composes all 17 tools as of step 23, including headless +handlers bound to the actual `HeadlessProcessGateway`. Missing project runtime +configuration fails at boot with `RUNTIME_UNAVAILABLE`; tool discovery does not +grant authority or launch a process. No fake runtime is shipped. DEV configuration-copy is connected as of step 21. The automated HTTP conformance gate exercises all 17 tool contracts using real project knowledge/LSP and test-only build/runtime ports; a separate HTTP test uses the real compiler/packer. This -completes MCP-phase conformance, not real-process or external-agent acceptance. +completes MCP-phase conformance. The packaged-runtime gate additionally exercises +actual app composition, project LSP, compiler/packer, saved edits, explicit +reset/reboot, build identity invalidation and corrective loops after compile +errors/guest faults. Full HTTP/visual and external-agent acceptance remain +subsequent integration gates, not implied by this service-composition gate. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it. diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 273cb769..1912d4cf 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -32,7 +32,7 @@ javafx { } // Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. -tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class") } +tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class") } tasks.register("devDesktopTest") { group = "verification" description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." @@ -63,5 +63,6 @@ tasks.register("headlessProcessTest") { classpath = sourceSets["test"].runtimeClasspath useJUnitPlatform() include("**/HeadlessInstalledRuntimeTest.class") + include("**/HeadlessTaskIntegrationTest.class") systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) } 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 461849ca..6bae6776 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -313,6 +313,11 @@ public class StudioApplicationConfiguration { return new p.studio.core.language.TaskLanguageQueries(projects, language); } + @Bean + p.studio.core.runtime.HeadlessGateway headlessGateway(ObjectMapper mapper, ProjectLocalStudioSetupStore setup) { + return new p.studio.app.runtime.HeadlessProcessGateway(mapper, setup::load); + } + @Bean p.studio.api.automation.TaskTools taskTools(p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, p.studio.core.shipper.SavedProjectPreparation shipper, 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 08ab12b0..4fd628d3 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -30,12 +30,13 @@ 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(8, tools.size()); + org.junit.jupiter.api.Assertions.assertEquals(17, 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()); assertTrue(tools.toString().contains("studio_language_query")); assertTrue(tools.toString().contains("studio_build_start")); - assertFalse(tools.toString().contains("studio_headless_boot")); + assertTrue(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 index d3b775ba..bcc31e44 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -56,7 +56,7 @@ class McpTaskToolsTest { } @AfterEach void close() throws Exception { buildGate.countDown(); - if (runtime != null) runtime.gate.countDown(); + if (runtime != null) { runtime.gate.countDown(); runtime.shutdownGate.complete(null); } session.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); workers.shutdownNow(); } @@ -70,7 +70,7 @@ class McpTaskToolsTest { 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); } + do { result = poll(request); if (result.path("workerTerminated").asBoolean()) return result; Thread.sleep(5); } while (System.nanoTime() < deadline); fail("Operation did not finish: " + result); return null; } @@ -156,6 +156,34 @@ class McpTaskToolsTest { assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); } + @Test void resetAllowsOnlyExplicitRebootOfTheSameKnownBuild() throws Exception { + acquire(); String build = buildAndBoot(); + var original = runtime; + error("BUSY", call("studio_headless_boot", args().put("buildId", build))); + value(call("studio_headless_reset", args())); + error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", "unknown"))); + value(call("studio_headless_boot", args().put("buildId", build))); + assertSame(original, runtime); + assertEquals(TaskTools.HeadlessAction.BOOT, runtime.lastAction); + error("BUSY", call("studio_headless_boot", args().put("buildId", build))); + } + + @Test void rebuildWaitsForShutdownAcknowledgementBeforeTouchingArtifacts() throws Exception { + acquire(); String build = buildAndBoot(); + runtime.shutdownGate = new CompletableFuture<>(); + failBuild = true; + value(call("studio_build_start", args().put("clientRequestId", "blocked-rebuild"))); + assertTrue(runtime.shutdownEntered.await(2, TimeUnit.SECONDS)); + assertEquals(1, builds.get()); + assertFalse(poll("blocked-rebuild").path("workerTerminated").asBoolean()); + error("BUSY", call("studio_headless_boot", args().put("buildId", build))); + runtime.shutdownGate.complete(null); + assertEquals("FAILED", completed("blocked-rebuild").path("result").path("status").asText()); + assertEquals(2, builds.get()); + error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", build))); + 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(); @@ -354,18 +382,22 @@ class McpTaskToolsTest { final String id = UUID.randomUUID().toString(), build; final AtomicInteger advances = new AtomicInteger(); final CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1); + final CountDownLatch shutdownEntered = new CountDownLatch(1); + CompletableFuture shutdownGate = CompletableFuture.completedFuture(null); + TaskTools.HeadlessAction lastAction; 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 CompletionStage shutdown() { shutdownEntered.countDown(); return shutdownGate.thenRun(() -> stopped = true); } 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; + lastAction = action; return new TaskTools.HeadlessReply(Map.of("sessionId", id), action == TaskTools.HeadlessAction.CAPTURE ? capture(5) : null); } public AutomationOutcome advance(long frames, Consumer progress) { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java index 56850efb..21a5ea7f 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java @@ -9,6 +9,8 @@ import java.util.*; /** Deliberately adversarial child process. Never packaged into production. */ public final class HeadlessFixture { static final ObjectMapper MAPPER = new ObjectMapper(); + // Allow normal JVM startup under load; call/cancel deadlines remain deliberately short. + static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 5000, 500, 150); static String mode; static void emit(JsonNode value) throws Exception { byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8); @@ -28,7 +30,7 @@ public final class HeadlessFixture { 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)); - hello.set("limits", MAPPER.valueToTree(new HeadlessLimits(600, 4096, 4096, 1000, 500, 150))); + hello.set("limits", MAPPER.valueToTree(LIMITS)); if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900); emit(hello); if (mode.equals("descendant")) { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java index 9fce1164..f5f5f7fc 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java @@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.*; class HeadlessProcessSessionTest { @TempDir Path root; - static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 1000, 500, 150); + static final HeadlessLimits LIMITS = HeadlessFixture.LIMITS; final List sessions = new ArrayList<>(); HeadlessProcessSession start(String mode) throws Exception { var process = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), mode).directory(root.toFile()).start(); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java new file mode 100644 index 00000000..cd7983b4 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java @@ -0,0 +1,176 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.api.session.*; +import p.studio.api.shipper.Shipper; +import p.studio.app.StudioApplicationConfiguration; +import p.studio.core.project.ProjectLocalStudioSetupStore; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.*; + +/** Actual app composition and saved-source services; no runtime/build/LSP doubles. */ +class HeadlessTaskIntegrationTest { + @TempDir Path root; + ConfigurableApplicationContext app; + ProjectSession project; + TaskTools tasks; + LanguageQueries language; + ObjectMapper mapper; + Path source; + String task, code; + final Set ownedProcesses = new HashSet<>(); + + @BeforeEach void open() throws Exception { + root = root.toRealPath(); + String installation = System.getProperty("studio.test.runtimeInstall", ""); + assertFalse(installation.isBlank(), "Supply -PstudioRuntimeInstall="); + app = new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(true).run(); + mapper = app.getBean(ObjectMapper.class); + for (var ref : p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game)) { + if (!ref.id().startsWith("pbs:example:game:1:")) continue; + Path file = root.resolve(ref.id().substring("pbs:example:game:1:".length())); + Files.createDirectories(file.getParent()); Files.writeString(file, ref.text()); + } + source = root.resolve("src/main.pbs"); code = Files.readString(source); + var reference = app.getBean(ProjectCatalog.class).openProject(root); + app.getBean(ProjectLocalStudioSetupStore.class).save(reference, new ProjectLocalStudioSetup(installation, null)); + project = app.getBean(ProjectSessionFactory.class).open(reference); + tasks = app.getBean(TaskTools.class); language = app.getBean(LanguageQueries.class); + assertTrue(project.automation().grant(false).toCompletableFuture().get(5, TimeUnit.SECONDS).success()); + task = tasks.acquire(root).task().value(); + } + + @AfterEach void close() { + try { if (project != null) project.close(); } + finally { if (app != null) app.close(); } + assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Managed runtime processes must stop on project closure"); + } + + TrackedOperation finished(String request) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + do { + var result = tasks.operation(root, task, new OperationLookup(null, request)); + if (result.workerTerminated()) return result; + Thread.sleep(5); + } while (System.nanoTime() < deadline); + throw new AssertionError("Operation did not finish: " + request); + } + TrackedOperation build(String request) throws Exception { + tasks.build(root, task, request); return finished(request); + } + String successfulBuild(String request) throws Exception { + var result = build(request); assertNull(result.failure()); + assertNotNull(result.buildResult()); assertTrue(result.buildResult().success(), result.buildResult().diagnostics().toString()); + assertNotNull(result.buildId()); return result.buildId(); + } + TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, String build) { + var reply = tasks.headless(root, task, action, build, Map.of()); + if (action == TaskTools.HeadlessAction.BOOT) { + String installation = Path.of(System.getProperty("studio.test.runtimeInstall")).toAbsolutePath().toString(); + ProcessHandle.current().descendants().filter(process -> process.info().command().orElse("").startsWith(installation + "/")) + .forEach(ownedProcesses::add); + assertFalse(ownedProcesses.isEmpty(), "Observe the actual packaged runtime process"); + } + return reply; + } + AutomationOutcome advance(String request) throws Exception { + tasks.advance(root, task, request, 3); + var result = finished(request); assertNull(result.failure(), String.valueOf(result.failure())); + assertNotNull(result.runtimeResult()); return result.runtimeResult(); + } + com.fasterxml.jackson.databind.JsonNode diagnostics() { + return mapper.valueToTree(language.query(root, task, "diagnostics", Map.of("uri", source.toUri().toString()))).path("result"); + } + void authorityRetained() { assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); } + + @Test void savedEditsRebuildRealArtifactsAndCorrelateDevWithoutSnapshots() throws Exception { + assertTrue(diagnostics().isEmpty()); + assertThrows(ControlDeniedException.class, () -> app.getBean(Shipper.class).prepare(project.projectReference(), ignored -> {})); + String first = successfulBuild("first"); + String session = (String) call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId"); + var initial = advance("initial"); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, initial.kind()); + assertEquals(first, initial.capture().buildId()); + assertArrayEquals(initial.capture().png(), project.automation().snapshot().capture().png()); + call(TaskTools.HeadlessAction.RESET, null); + assertTrue(project.automation().snapshot().stale()); + assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class, + () -> call(TaskTools.HeadlessAction.CAPTURE, null)).failure().code()); + assertEquals(session, call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId")); + assertArrayEquals(initial.capture().png(), advance("rebooted").capture().png()); + + // Native agent-style edit: same project files, no clean-tree or apply step. + Files.writeString(source, code.replace("Color.rgb(16, 20, 28)", "Color.rgb(80, 40, 20)")); + assertTrue(diagnostics().isEmpty()); + String second = successfulBuild("second"); + assertNotEquals(first, second); + assertTrue(project.automation().snapshot().stale()); + assertTrue(finished("initial").captureStale()); + assertEquals(AutomationFailure.Code.SESSION_NOT_FOUND, assertThrows(AutomationException.class, + () -> call(TaskTools.HeadlessAction.STATE, null)).failure().code()); + assertEquals(AutomationFailure.Code.BUILD_NOT_FOUND, assertThrows(AutomationException.class, + () -> call(TaskTools.HeadlessAction.BOOT, first)).failure().code()); + assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Rebuild must stop the previous runtime"); + assertNotEquals(session, call(TaskTools.HeadlessAction.BOOT, second).values().get("sessionId")); + var changed = advance("changed"); + assertFalse(Arrays.equals(initial.capture().png(), changed.capture().png())); + assertEquals(second, project.automation().snapshot().capture().buildId()); + assertFalse(project.automation().snapshot().stale()); + authorityRetained(); + assertTrue(tasks.release(root, task).toCompletableFuture().get(7, TimeUnit.SECONDS).success()); + assertTrue(project.automation().snapshot().manualAllowed()); + assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Release must stop the runtime before returning control"); + assertTrue(Files.readString(source).contains("Color.rgb(80, 40, 20)")); + } + + @Test void compileAndGuestFailuresKeepAuthorityForCorrectiveBuilds() throws Exception { + String original = successfulBuild("original"); + call(TaskTools.HeadlessAction.BOOT, original); advance("before-error"); + Files.writeString(source, "fn frame( {"); + assertFalse(diagnostics().isEmpty()); + var failed = build("compile-error"); + assertFalse(failed.buildResult().success()); assertNull(failed.buildId()); + assertFalse(failed.buildResult().diagnostics().isEmpty()); + assertFalse(project.automation().snapshot().diagnostics().isEmpty()); + assertTrue(project.automation().snapshot().stale()); authorityRetained(); + assertEquals(AutomationFailure.Code.BUILD_NOT_FOUND, assertThrows(AutomationException.class, + () -> call(TaskTools.HeadlessAction.BOOT, original)).failure().code()); + + Files.writeString(source, code.replace("x = x + 1;", "x = x / (x - x);")); + assertTrue(diagnostics().isEmpty()); + call(TaskTools.HeadlessAction.BOOT, successfulBuild("guest-error")); + var fault = advance("fault"); + assertEquals(AutomationOutcome.Kind.GUEST_FAULT, fault.kind()); + assertFalse(fault.diagnostics().isEmpty()); + assertNotNull(call(TaskTools.HeadlessAction.FAULT, null).values().get("fault")); + authorityRetained(); + + Files.writeString(source, code); + assertTrue(diagnostics().isEmpty()); + call(TaskTools.HeadlessAction.BOOT, successfulBuild("corrected")); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("working-again").kind()); + authorityRetained(); + } + + @Test void unavailableRuntimeIsExplicitAndCanBeConfiguredWithinTheSameTask() throws Exception { + String build = successfulBuild("build"); + var setup = app.getBean(ProjectLocalStudioSetupStore.class); + setup.save(project.projectReference(), ProjectLocalStudioSetup.defaults()); + assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class, + () -> call(TaskTools.HeadlessAction.BOOT, build)).failure().code()); + authorityRetained(); + setup.save(project.projectReference(), new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"), null)); + call(TaskTools.HeadlessAction.BOOT, build); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("configured").kind()); + authorityRetained(); + } +} 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 index 8a36632e..3e52f391 100644 --- 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 @@ -121,22 +121,29 @@ public final class DefaultTaskTools implements TaskTools { 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"); + if (data.runtime != null && !data.reset) 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); + if (data.runtime != null) { + if (!buildId.equals(data.runtimeBuildId)) throw failure(AutomationFailure.Code.BUILD_NOT_FOUND, "Reset session belongs to another build"); + result = data.runtime.call(HeadlessAction.BOOT, Map.of()); + } else { + 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; + data.runtimeBuildId = buildId; + result = new HeadlessReply(Map.of("sessionId", runtime.sessionId(), "buildId", buildId), null); + } + data.reset = false; } 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(); + if (action == HeadlessAction.RESET) { data.reset = true; session.markCaptureStale(); } } reply.set(result); return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), result.capture()); @@ -150,6 +157,7 @@ public final class DefaultTaskTools implements TaskTools { handle.cancel(); Thread.currentThread().interrupt(); throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call interrupted"); } catch (ExecutionException error) { + handle.termination().toCompletableFuture().join(); if (error.getCause() instanceof RuntimeException cause) throw cause; throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call failed"); } catch (CancellationException error) { @@ -164,6 +172,8 @@ public final class DefaultTaskTools implements TaskTools { runtime.shutdown().toCompletableFuture().join(); data.session.detachRuntime(data.task, runtime); data.runtime = null; + data.runtimeBuildId = null; + data.reset = false; } private TaskData data(AutomationSession session, String id) { @@ -229,6 +239,8 @@ public final class DefaultTaskTools implements TaskTools { final Map requests = new HashMap<>(), operations = new HashMap<>(); final Map builds = new ConcurrentHashMap<>(); volatile HeadlessGateway.Session runtime; + String runtimeBuildId; + boolean reset; TaskData(AutomationSession session, TaskIdentity task) { this.session = session; this.task = task; } } } From 4f148a50dea41ac4cfbe4eeac3362c754dffb355 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 11:40:02 +0100 Subject: [PATCH 10/15] verify real MCP runtime and DEV framebuffer parity --- README.md | 22 +- ...CP Tools and Project Knowledge Contract.md | 30 +- prometeu-app/build.gradle.kts | 13 +- .../app/runtime/DirectHeadlessOracle.java | 73 +++++ .../app/runtime/HeadlessMcpDesktopTest.java | 280 ++++++++++++++++++ .../javafx/workspaces/dev/DevWorkspace.java | 1 + .../dev/DevWorkspaceProjectionTest.java | 9 + 7 files changed, 419 insertions(+), 9 deletions(-) create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/DirectHeadlessOracle.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java diff --git a/README.md b/README.md index 8679dd72..46ceb89a 100644 --- a/README.md +++ b/README.md @@ -74,8 +74,26 @@ This gate builds an installed PBS example, launches the actual runtime, checks canonical PNGs and explicit reset/reboot, cancels an advance and verifies process cleanup. It also runs the actual app composition through saved-file LSP queries, rebuilds and corrective loops after compile errors and guest faults. It does not -download a runtime or substitute a protocol fixture. Full HTTP/visual integration -and external-agent acceptance remain subsequent integration gates. +download a runtime or substitute a protocol fixture. + +To verify the complete HTTP-to-runtime-to-DEV image path, run this separate gate +in a desktop environment: + +```bash +./gradlew :prometeu-app:headlessMcpDesktopTest -PstudioRuntimeInstall=/absolute/path/to/runtime --max-workers=2 +``` + +It opens the real DEV view, grants control, uses an HTTP MCP client to query LSP, +edit/build the installed PBS example and execute a fixed input timeline. PNG bytes, +frame identities, state and fault are compared with a separate direct-JSONL runtime +process; every decoded ImageView pixel and its visible identity/stale label are +checked. Reset, fresh-session repetition and rebuild are included. This automated +client is not the external coding-agent acceptance gate. + +Known language limitation: definition lookup for the bundled SDK's `Input.pad()` +currently returns no location. Project-source navigation and indexed SDK reference +reads work; an empty definition result must not be interpreted as missing runtime +support or permission to edit the SDK. ## Requirements 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 65ba939c..d965626b 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 @@ -425,8 +425,8 @@ compression/padding. Logical and render frame counters are independent. The adapter MUST NOT invent a frame when none exists or substitute another session's image. The same neutral capture feeds DEV and MCP. Real runtime -production/cross-language equality remain phase 4 gates; encoding test pixels in -contract tests does not satisfy that integration requirement. +production/cross-language equality is verified by the phase 4 desktop integration +gate below; encoding test pixels in contract tests alone does not satisfy it. ## 7. Conformance and Delivery Boundary @@ -448,7 +448,25 @@ build/runtime ports; a separate HTTP test uses the real compiler/packer. This completes MCP-phase conformance. The packaged-runtime gate additionally exercises actual app composition, project LSP, compiler/packer, saved edits, explicit reset/reboot, build identity invalidation and corrective loops after compile -errors/guest faults. Full HTTP/visual and external-agent acceptance remain -subsequent integration gates, not implied by this service-composition gate. -API/Core and -JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it. +errors/guest faults. + +Step 24 adds `headlessMcpDesktopTest`: a real HTTP client drives the composed app, +installed compiler/packer/LSP and packaged Rust runtime, while the actual JavaFX +DEV view observes the shared session. An independent test-only JSONL client runs +the same saved cartridge and input timeline in another real process, without the +Studio process adapter or capture DTOs. Raw PNG bytes and each capture metadata +field match MCP; all decoded framebuffer pixels and the visible identity/stale +labels match DEV. State/fault and deterministic reset/fresh-session repetitions +are also checked. Rebuilding changes pixels/build identity and visibly marks the +old capture stale. Images remain in memory; window screenshots are not evidence. + +The fixture uses supported project-source LSP definition/symbol navigation and +indexed SDK reads. A probe of the installed SDK's `Input.pad()` definition returns +an empty result with the current language service; the gate does not claim SDK +symbol navigation where no location is returned. This is a language tooling +limitation, not a headless or MCP execution fallback. + +The automated client is not an external coding agent. Adversarial integrated +lifecycle, real-agent compatibility and final packaging acceptance remain later +gates. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture +tests enforce it. diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 1912d4cf..269af92d 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -32,7 +32,7 @@ javafx { } // Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. -tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class") } +tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class") } tasks.register("devDesktopTest") { group = "verification" description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." @@ -66,3 +66,14 @@ tasks.register("headlessProcessTest") { include("**/HeadlessTaskIntegrationTest.class") systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) } + +tasks.register("headlessMcpDesktopTest") { + group = "verification" + description = "Proves HTTP MCP, packaged runtime and actual DEV framebuffer parity (requires a display and -PstudioRuntimeInstall)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/HeadlessMcpDesktopTest.class") + systemProperty("java.awt.headless", "false") + systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/DirectHeadlessOracle.java b/prometeu-app/src/test/java/p/studio/app/runtime/DirectHeadlessOracle.java new file mode 100644 index 00000000..c19e9b9e --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/DirectHeadlessOracle.java @@ -0,0 +1,73 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Independent test-only JSONL client: no Studio gateway/DTO/capture transformation. */ +final class DirectHeadlessOracle implements AutoCloseable { + private final ObjectMapper mapper = new ObjectMapper(); + private final Process process; + private final BufferedReader output; + private final BufferedWriter input; + private final ExecutorService reader = Executors.newVirtualThreadPerTaskExecutor(); + private final Set descendants = new HashSet<>(); + private String session; + + DirectHeadlessOracle(Path installation, Path cartridge) throws Exception { + process = new ProcessBuilder(installation.resolve(System.getProperty("os.name").startsWith("Windows") ? "prometeu.exe" : "prometeu").toString(), + "headless", "--stdio").redirectError(ProcessBuilder.Redirect.DISCARD).start(); + output = process.inputReader(StandardCharsets.UTF_8); + input = process.outputWriter(StandardCharsets.UTF_8); + try { + var hello = event(); + assertEquals("hello", hello.path("type").asText()); + session = hello.path("sessionId").asText(); assertFalse(session.isBlank()); + assertEquals(1, hello.path("protocolVersion").path("major").asInt()); + var initialize = mapper.createObjectNode(); + initialize.putObject("protocolVersion").put("major", 1).put("minor", 0); + initialize.set("requiredCapabilities", hello.path("capabilities")); + call("initialize", initialize); + call("boot", mapper.createObjectNode().put("path", cartridge.toString())); + } catch (Throwable failure) { terminate(); throw failure; } + } + private JsonNode event() throws Exception { + String line = reader.submit(output::readLine).get(10, TimeUnit.SECONDS); + assertNotNull(line, "Runtime stdout closed before reply"); + process.descendants().forEach(descendants::add); + return mapper.readTree(line); + } + JsonNode call(String command, JsonNode params) throws Exception { + String id = UUID.randomUUID().toString(); + var request = mapper.createObjectNode().put("requestId", id).put("command", command).set("params", params); + input.write(request.toString()); input.newLine(); input.flush(); + while (true) { + var response = event(); + assertEquals(session, response.path("sessionId").asText()); + assertEquals(id, response.path("requestId").asText()); + if (response.path("type").asText().equals("progress")) continue; + assertEquals("response", response.path("type").asText()); + assertFalse(response.has("error"), response.toString()); + return response.path("result"); + } + } + JsonNode call(String command) throws Exception { return call(command, mapper.createObjectNode()); } + private void terminate() { + process.descendants().forEach(descendants::add); + descendants.forEach(ProcessHandle::destroyForcibly); process.destroyForcibly(); reader.shutdownNow(); + try { + assertTrue(process.waitFor(5, TimeUnit.SECONDS)); + for (var child : descendants) child.onExit().get(5, TimeUnit.SECONDS); + } catch (Exception failure) { throw new AssertionError("Oracle process cleanup failed", failure); } + } + @Override public void close() throws Exception { + try { + assertTrue(call("shutdown").path("closed").asBoolean()); + assertTrue(process.waitFor(5, TimeUnit.SECONDS)); + } finally { terminate(); } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java new file mode 100644 index 00000000..fbfe576d --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java @@ -0,0 +1,280 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.ObjectNode; +import javafx.application.Platform; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.image.ImageView; +import javafx.stage.Stage; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.api.session.*; +import p.studio.app.StudioApplicationConfiguration; +import p.studio.app.mcp.LocalMcpServer; +import p.studio.core.project.ProjectLocalStudioSetupStore; +import p.studio.ui.javafx.events.StudioEventBus; +import p.studio.ui.javafx.utilities.i18n.*; +import p.studio.ui.javafx.workspaces.dev.DevWorkspace; +import java.io.ByteArrayInputStream; +import java.net.http.*; +import java.nio.file.*; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Full real loop: external HTTP client -> app -> Rust JSONL -> MCP image and JavaFX DEV. */ +class HeadlessMcpDesktopTest { + @TempDir Path root; + final ObjectMapper mapper = new ObjectMapper(); + final Set owned = new HashSet<>(); + ConfigurableApplicationContext app; + ProjectSession project; + LocalMcpServer server; + HttpClient client; + String connection, task, build, session; + Path installation, source; + DevWorkspace dev; + Stage stage; + I18nService locale; + + @BeforeAll static void toolkit() throws Exception { + var ready = new CompletableFuture(); + Platform.startup(() -> { Platform.setImplicitExit(false); ready.complete(null); }); + ready.get(10, TimeUnit.SECONDS); + } + @AfterAll static void stopToolkit() { Platform.exit(); } + static void fx(Runnable work) throws Exception { + var completed = new CompletableFuture(); + Platform.runLater(() -> { try { work.run(); completed.complete(null); } catch (Throwable failure) { completed.completeExceptionally(failure); } }); + completed.get(10, TimeUnit.SECONDS); + } + @BeforeEach void open() throws Exception { + String configured = System.getProperty("studio.test.runtimeInstall", ""); + assertFalse(configured.isBlank(), "Supply -PstudioRuntimeInstall="); + installation = Path.of(configured).toRealPath(); root = root.toRealPath(); + app = new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(false).run(); + for (var ref : p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game)) { + if (!ref.id().startsWith("pbs:example:game:1:")) continue; + Path file = root.resolve(ref.id().substring("pbs:example:game:1:".length())); + Files.createDirectories(file.getParent()); Files.writeString(file, ref.text()); + } + source = root.resolve("src/main.pbs"); + var reference = app.getBean(ProjectCatalog.class).openProject(root); + app.getBean(ProjectLocalStudioSetupStore.class).save(reference, new ProjectLocalStudioSetup(installation.toString(), null)); + project = app.getBean(ProjectSessionFactory.class).open(reference); + server = app.getBean(LocalMcpServer.class); client = HttpClient.newHttpClient(); + fx(() -> { + locale = new I18nService(); locale.setLocale(Locale.ENGLISH); + dev = new DevWorkspace(reference, project.automation(), locale, new StudioEventBus(), app.getBean(AgentConnectionGuide.class)); + stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance"); + stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load(); + }); + var initialize = request("initialize"); + var params = initialize.putObject("params").put("protocolVersion", "2025-06-18"); + params.putObject("capabilities"); params.putObject("clientInfo").put("name", "real-loop-test").put("version", "1"); + var response = post(initialize); assertEquals(200, response.statusCode()); + connection = response.headers().firstValue("Mcp-Session-Id").orElseThrow(); + assertEquals(202, post(mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized")).statusCode()); + } + @AfterEach void close() throws Exception { + try { fx(() -> { if (dev != null) dev.unLoad(); if (stage != null) stage.close(); }); } + finally { + try { if (project != null) project.close(); } + finally { if (client != null) client.close(); if (app != null) app.close(); } + } + assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "No managed runtime may survive the test"); + } + + @Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception { + assertEquals(17, 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))); + assertTrue(sdk.toString().contains("InputPad"), "Consult installed SDK source through the indexed read-only reference"); + assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText()); + fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire()); + assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state()); + task = value(call("studio_control_acquire", args())).path("taskId").asText(); + assertFalse(task.isBlank()); + // Agent-native edit of the installed example; SDK remains unchanged. + String edited = Files.readString(source).replace("import { Gfx } from @sdk:gfx;", + "import { Gfx } from @sdk:gfx;\nimport { Input } from @sdk:input;") + .replace("x = x + 1;", "if (Input.pad().right().down()) { x = x + 3; } else { x = x + 1; }"); + Files.writeString(source, edited); + var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString()); + assertTrue(value(call("studio_language_query", query)).path("result").isEmpty()); + var symbols = args().put("operation", "documentSymbols"); symbols.putObject("parameters").put("uri", source.toUri().toString()); + assertTrue(value(call("studio_language_query", symbols)).path("result").toString().contains("frame")); + int inputOffset = edited.indexOf("x = x + 3;") + "x = ".length(); + String preceding = edited.substring(0, inputOffset); + var definition = args().put("operation", "definition"); + definition.putObject("parameters").put("uri", source.toUri().toString()).putObject("position") + .put("line", preceding.chars().filter(c -> c == '\n').count()) + .put("character", inputOffset - preceding.lastIndexOf('\n') - 1); + var locations = value(call("studio_language_query", definition)).path("result"); + assertFalse(locations.isEmpty(), "Navigate the saved PBS source through the actual LSP"); + assertEquals(source.toUri().toString(), locations.get(0).path("uri").asText()); + build("first-build"); boot(); + assertEquals("NO_FRAME_AVAILABLE", call("studio_headless_capture", args()).path("structuredContent").path("error").path("code").asText()); + + List first; + try (var oracle = new DirectHeadlessOracle(installation, root.resolve("build"))) { + first = timeline("first", oracle); + } + value(call("studio_headless_reset", args())); assertStale(true); + String previousSession = session; boot(); assertEquals(previousSession, session); + try (var oracle = new DirectHeadlessOracle(installation, root.resolve("build"))) { + assertSameTimeline(first, timeline("reset", oracle)); + } + value(call("studio_headless_shutdown", args())); assertStale(true); + boot(); assertNotEquals(previousSession, session); + try (var oracle = new DirectHeadlessOracle(installation, root.resolve("build"))) { + assertSameTimeline(first, timeline("fresh", oracle)); + } + + String oldBuild = build; + Files.writeString(source, edited.replace("Color.rgb(16, 20, 28)", "Color.rgb(80, 40, 20)")); + assertTrue(value(call("studio_language_query", query)).path("result").isEmpty()); + build("rebuild"); assertNotEquals(oldBuild, build); assertStale(true); + var historical = value(call("studio_operation_get", args().put("clientRequestId", "fresh-0"))); + assertTrue(historical.path("capture").path("stale").asBoolean()); + boot(); + try (var oracle = new DirectHeadlessOracle(installation, root.resolve("build"))) { + var rebuilt = timeline("rebuilt", oracle); + assertFalse(Arrays.equals(png(first.getFirst()), png(rebuilt.getFirst()))); + } + value(call("studio_control_release", args())); + assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); assertStale(true); + fx(() -> assertFalse(((Button) dev.rootNode().lookup("#dev-grant")).isDisabled())); + assertTrue(Files.readString(source).contains("Color.rgb(80, 40, 20)")); + } + + List timeline(String prefix, DirectHeadlessOracle oracle) throws Exception { + // RIGHT held for two frames, released for one, held for another three. + int[] frames = {2, 1, 3}; int[] logical = {2, 3, 6}; int[] x = {3, 6, 13}; + var captures = new ArrayList(); + for (int i = 0; i < frames.length; i++) { + if (i == 1) { value(call("studio_headless_clear_input", args())); oracle.call("clear_input"); } + else { + var input = mapper.createObjectNode().put("right", true); + value(call("studio_headless_set_input", args().set("input", input))); oracle.call("set_input", input); + } + String requestId = prefix + "-" + i; + var receipt = value(call("studio_headless_advance", args().put("clientRequestId", requestId).put("frames", frames[i]))); + var result = completed(requestId); + assertEquals("SUCCEEDED", value(result).path("result").path("status").asText()); + assertEquals(frames[i], value(result).path("progress").path("completedFrames").asInt()); + // Retrying the same receipt must not execute another batch of frames. + assertEquals(receipt.path("operationId"), value(call("studio_headless_advance", + args().put("clientRequestId", requestId).put("frames", frames[i]))).path("operationId")); + var advanced = oracle.call("advance", mapper.createObjectNode().put("frames", frames[i])); + assertEquals("completed", advanced.path("stop").asText()); + var raw = oracle.call("capture"); + var image = call("studio_headless_capture", args()); + assertArrayEquals(png(result), png(image)); + assertEquals(value(result).path("capture"), value(image)); + compareCapture(raw, image, logical[i], x[i]); + captures.add(raw.deepCopy()); + var actualState = value(call("studio_headless_state", args())).path("state"); + assertEquals(oracle.call("get_state"), actualState); + assertEquals(oracle.call("get_fault"), value(call("studio_headless_fault", args())).path("fault")); + } + return captures; + } + void compareCapture(JsonNode raw, JsonNode image, int logical, int rectangleX) throws Exception { + var metadata = value(image); + for (String field : List.of("logicalFrameIndex", "frameId", "width", "height", "stridePixels", "pixelFormat", "mimeType")) + assertEquals(raw.path(field), metadata.path(field), field); + assertEquals(logical, metadata.path("logicalFrameIndex").asInt()); + assertEquals(build, metadata.path("buildId").asText()); assertEquals(session, metadata.path("sessionId").asText()); + byte[] expected = Base64.getDecoder().decode(raw.path("data").asText()); + assertArrayEquals(expected, png(image)); + final java.awt.image.BufferedImage decoded; + try (var encoded = new javax.imageio.stream.MemoryCacheImageInputStream(new ByteArrayInputStream(expected))) { + var decoder = javax.imageio.ImageIO.getImageReaders(encoded).next(); + try { decoder.setInput(encoded); decoded = decoder.read(0); } + finally { decoder.dispose(); } + } + int width = decoded.getWidth(), height = decoded.getHeight(); + assertEquals(metadata.path("width").asInt(), width); assertEquals(metadata.path("height").asInt(), height); + assertEquals(0xfff0a030, decoded.getRGB(rectangleX, 32)); // Actual input-sensitive rectangle, not only matching blank images. + assertNotEquals(0xfff0a030, decoded.getRGB(rectangleX - 1, 32)); + int[] pixels = decoded.getRGB(0, 0, width, height, null, 0, width); + var snapshot = project.automation().snapshot(); + assertArrayEquals(expected, snapshot.capture().png()); + assertEquals(metadata.path("frameId").bigIntegerValue(), snapshot.capture().frameId()); + fx(() -> { + var canvas = (ImageView) dev.rootNode().lookup("#dev-framebuffer"); + assertNotNull(canvas.getImage()); assertFalse(canvas.getImage().isError()); + assertEquals(width, (int) canvas.getImage().getWidth()); assertEquals(height, (int) canvas.getImage().getHeight()); + var reader = canvas.getImage().getPixelReader(); + int[] displayed = new int[width * height]; + reader.getPixels(0, 0, width, height, javafx.scene.image.PixelFormat.getIntArgbInstance(), displayed, 0, width); + assertArrayEquals(pixels, displayed, "Every displayed framebuffer pixel must match the Rust PNG"); + assertFalse(canvas.isSmooth()); + String label = ((Label) dev.rootNode().lookup("#dev-capture-identity")).getText(); + assertEquals("session=" + session + " | build=" + build + " | logical=" + logical + + " | FrameId=" + metadata.path("frameId").asText() + " | " + width + "×" + height + + " | stride=" + metadata.path("stridePixels").asText(), label); + }); + assertStale(false); + } + void assertStale(boolean stale) throws Exception { + assertEquals(stale, project.automation().snapshot().stale()); + fx(() -> assertEquals(locale.text(stale ? I18n.DEV_STALE_FRAME : I18n.DEV_CURRENT_FRAME), + ((Label) dev.rootNode().lookup("#dev-image-status")).getText())); + } + void assertSameTimeline(List expected, List actual) { + assertEquals(expected, actual, "Raw runtime captures, pixels and both frame identities repeat exactly"); + } + void build(String requestId) throws Exception { + value(call("studio_build_start", args().put("clientRequestId", requestId))); + var result = value(completed(requestId)).path("result"); + assertEquals("SUCCESS", result.path("status").asText(), result.toString()); + build = result.path("buildId").asText(); assertFalse(build.isBlank()); + } + void boot() throws Exception { + session = value(call("studio_headless_boot", args().put("buildId", build))).path("sessionId").asText(); + assertFalse(session.isBlank()); + ProcessHandle.current().descendants().filter(p -> p.info().command().orElse("").startsWith(installation + "/")).forEach(owned::add); + assertFalse(owned.isEmpty(), "Observe the actual packaged runtime, not an in-process replacement"); + } + JsonNode completed(String id) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + do { + var reply = call("studio_operation_get", args().put("clientRequestId", id)); + var result = value(reply); + if (result.path("workerTerminated").asBoolean()) { assertTrue(result.path("failure").isNull(), result.toString()); return reply; } + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("Operation did not finish: " + id); + } + ObjectNode args() { var args = mapper.createObjectNode().put("projectRoot", root.toString()); if (task != null) args.put("taskId", task); return args; } + ObjectNode request(String method) { return mapper.createObjectNode().put("jsonrpc", "2.0").put("id", UUID.randomUUID().toString()).put("method", method); } + JsonNode call(String name, ObjectNode args) throws Exception { + var request = request("tools/call"); request.putObject("params").put("name", name).set("arguments", args); + var response = post(request); assertEquals(200, response.statusCode()); + var body = mapper.readTree(response.body()); assertFalse(body.has("error"), body.toString()); return body.path("result"); + } + HttpResponse post(JsonNode body) throws Exception { + var request = HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15)) + .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(HttpRequest.BodyPublishers.ofString(body.toString())).build(), HttpResponse.BodyHandlers.ofString()); + } + JsonNode value(JsonNode result) { assertFalse(result.path("isError").asBoolean(), result.toString()); return result.path("structuredContent").path("value"); } + byte[] png(JsonNode result) { + if (result.has("data")) return Base64.getDecoder().decode(result.path("data").asText()); + assertEquals("image", result.path("content").get(1).path("type").asText()); + assertEquals("image/png", result.path("content").get(1).path("mimeType").asText()); + return Base64.getDecoder().decode(result.path("content").get(1).path("data").asText()); + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java index b1fe3936..f3585aac 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java @@ -46,6 +46,7 @@ public final class DevWorkspace extends Workspace { scroll.setFitToWidth(true); root.setPadding(new Insets(16)); root.getStyleClass().add("dev-workspace"); grant.setId("dev-grant"); reclaim.setId("dev-reclaim"); + canvas.setId("dev-framebuffer"); identity.setId("dev-capture-identity"); imageStatus.setId("dev-image-status"); grant.textProperty().bind(i18n.bind(I18n.DEV_GRANT)); reclaim.textProperty().bind(i18n.bind(I18n.DEV_RECLAIM)); grant.setOnAction(e -> grant(false)); diff --git a/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java b/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java index cf26fa4c..b03e7744 100644 --- a/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java +++ b/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java @@ -25,6 +25,15 @@ class DevWorkspaceProjectionTest { assertTrue(view.identity().contains("session-A")); assertTrue(view.identity().contains("build-B")); assertEquals("diagnostic", view.diagnostics()); assertEquals("call", view.calls()); } + @Test void projectionDoesNotNarrowUnsignedFrameIdentities() { + var logical = new java.math.BigInteger("18446744073709551615"); + var render = new java.math.BigInteger("9223372036854775808"); + var frame = new CanonicalCapture("session", "build", logical, render, 2, 1, 3, new byte[]{1}); + var view = DevWorkspaceProjection.from(snapshot(ControlState.AGENT_WORKING, frame, false, false)); + assertSame(frame, view.capture()); + assertEquals("session=session | build=build | logical=18446744073709551615 | FrameId=9223372036854775808 | 2×1 | stride=3", view.identity()); + assertFalse(view.stale()); + } private AutomationSnapshot snapshot(ControlState state, CanonicalCapture frame, boolean stale, boolean closed) { return new AutomationSnapshot(Path.of("."), state, false, closed, 0, null, null, frame, stale, List.of("diagnostic"), List.of("call")); } From e6a83c94e0ce9d04ab808158d1affc068a09eea7 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 12:06:48 +0100 Subject: [PATCH 11/15] verify automation interruption recovery and manual debug lifecycle --- README.md | 26 ++- .../10. DEV and Automation Specification.md | 13 ++ ...CP Tools and Project Knowledge Contract.md | 20 +- prometeu-app/build.gradle.kts | 2 +- .../app/StudioApplicationConfiguration.java | 4 +- .../app/runtime/HeadlessProcessSession.java | 18 +- .../app/runtime/HeadlessMcpDesktopTest.java | 177 ++++++++++++++++++ .../runtime/HeadlessProcessSessionTest.java | 1 + .../session/DefaultProjectSessionFactory.java | 26 ++- .../session/DefaultProjectSessionTest.java | 30 +++ 10 files changed, 300 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 46ceb89a..79707f09 100644 --- a/README.md +++ b/README.md @@ -90,10 +90,28 @@ process; every decoded ImageView pixel and its visible identity/stale label are checked. Reset, fresh-session repetition and rebuild are included. This automated client is not the external coding-agent acceptance gate. -Known language limitation: definition lookup for the bundled SDK's `Input.pad()` -currently returns no location. Project-source navigation and indexed SDK reference -reads work; an empty definition result must not be interpreted as missing runtime -support or permission to edit the SDK. +The same suite also exercises cancellation, disconnect/reconnect, revocation, +project/app closure, crash and forced shutdown, corrective builds, and return to +the real manual Debug host. These scenarios require a POSIX desktop (validated +on macOS ARM64) and free port 7777. Only processes created by the test are killed +or suspended. After a forced-shutdown error, an explicit second reclaim can +acknowledge completed cleanup; control stays locked until cleanup is confirmed. + +### Follow-ups after the AI-first implementation + +The following findings are recorded for investigation after implementation; they +are not considered fixed by the passing integration tests: + +- **PBS/LSP SDK navigation:** definition lookup for the bundled SDK's `Input.pad()` + currently returns no location. Project-source navigation and indexed SDK reference + reads work. Investigate SDK symbol resolution separately; an empty definition + result is not evidence of missing runtime support or permission to edit the SDK. +- **Build tooling:** the validation environment's JDK 25 triggers Kotlin's target-24 + fallback and Java/Kotlin target compatibility warnings in `buildSrc`. The targeted + regression passes, but the toolchain/target alignment needs separate review. + +Cross-platform desktop coverage and real external-client acceptance are remaining +validation boundaries, not confirmed product defects. ## Requirements diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md index b35972a6..e0a8e881 100644 --- a/docs/specs/studio/10. DEV and Automation Specification.md +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -139,6 +139,19 @@ NOT release control. Closing the project or Studio MUST revoke authority and stop managed processes before teardown of their providers/executors. Reopening MUST start in manual control, even when restoring DEV as the selected workspace. +The application-owned project-session factory tracks sessions and closes all of +them before its LSP/executor dependencies are destroyed, including sessions not +currently represented by a window. Closing one project removes it from that set; +application teardown rejects new opens and attempts every remaining project even +if another close reports failure. + +If shutdown required forced termination, the first return attempt reports cleanup +failure and retains the manual guard. A subsequent explicit human reclaim may +acknowledge cleanup only after the gateway confirms that its owned process tree +is dead. A cached failed shutdown must not make a dead session permanently +unreclaimable. Cancellation racing a process crash must still allow the owner to +await worker termination and shutdown; it must not bypass that cleanup sequence. + Studio cannot stop direct writes by the external coding client. The UI and connection instructions MUST tell the developer to stop that client separately; reclaim is not an operating-system filesystem lock or a rollback guarantee. 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 d965626b..02e8d663 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 @@ -466,7 +466,19 @@ an empty result with the current language service; the gate does not claim SDK symbol navigation where no location is returned. This is a language tooling limitation, not a headless or MCP execution fallback. -The automated client is not an external coding agent. Adversarial integrated -lifecycle, real-agent compatibility and final packaging acceptance remain later -gates. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture -tests enforce it. +Step 25 extends that real desktop/HTTP gate with active-operation cancellation, +connection deletion/reconnection and duplicate receipts, waiting/active revoke, +late-call rejection, project closure/reopening and application-context shutdown. +A controlled document participant delays refresh acknowledgement to prove that +manual control remains blocked until process cleanup and disk refresh complete; +it also checks that no revoked frame or old source buffer is applied afterward. +The real runtime is killed or suspended in test-owned processes to verify known +progress, no implicit restart/replay, forced cleanup and explicit human retry. +Compile errors and guest faults are corrected over HTTP within the same task. +The normal desktop Debug process starts after release and blocks a new grant. +The suspension/manual-Debug scenarios require a POSIX desktop and a free Debug +port 7777; the gate never attaches to an existing user's Debug process. + +The automated client is not an external coding agent. Real-agent compatibility +and final packaging acceptance remain later gates. API/Core and JavaFX MUST NOT +import MCP/HTTP implementations; architecture tests enforce it. diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 269af92d..8df792af 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -69,7 +69,7 @@ tasks.register("headlessProcessTest") { tasks.register("headlessMcpDesktopTest") { group = "verification" - description = "Proves HTTP MCP, packaged runtime and actual DEV framebuffer parity (requires a display and -PstudioRuntimeInstall)." + description = "Proves MCP/runtime/DEV parity and adversarial lifecycle (requires POSIX desktop, free Debug port 7777 and -PstudioRuntimeInstall)." testClassesDirs = sourceSets["test"].output.classesDirs classpath = sourceSets["test"].runtimeClasspath useJUnitPlatform() 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 6bae6776..69aec83e 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -227,8 +227,8 @@ public class StudioApplicationConfiguration { return new p.studio.core.project.ProjectAccessRegistry(); } - @Bean - ProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore, + @Bean(destroyMethod = "close") + DefaultProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore, ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) { return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations); diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java index ded75db0..ffb592ed 100644 --- a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java @@ -141,11 +141,23 @@ final class HeadlessProcessSession implements HeadlessGateway.Session { var target = advance.get(); if (target == null || target.result.isDone() || !target.cancelled.compareAndSet(false, true) || dead.get()) return; var cancel = new Pending("cancel", null, null); - send(cancel, mapper.createObjectNode().put("targetRequestId", target.id)); - timer.schedule(() -> { if (!target.result.isDone() || !cancel.result.isDone()) abort("Runtime did not stop after cancellation"); }, limits.shutdownTimeoutMs(), TimeUnit.MILLISECONDS); + try { + send(cancel, mapper.createObjectNode().put("targetRequestId", target.id)); + timer.schedule(() -> { if (!target.result.isDone() || !cancel.result.isDone()) abort("Runtime did not stop after cancellation"); }, limits.shutdownTimeoutMs(), TimeUnit.MILLISECONDS); + } catch (RuntimeException lost) { + // A concurrent crash may close the writer/timer. Fail the pending operation, + // but do not prevent the authority owner from awaiting shutdown and cleanup. + abort("Headless session lost during cancellation"); + } } @Override public synchronized CompletionStage shutdown() { - if (shutdown != null) return shutdown; + 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; + } closing = true; shutdown = CompletableFuture.runAsync(() -> { long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.shutdownTimeoutMs()); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java index fbfe576d..fd1fc7a3 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java @@ -76,6 +76,10 @@ class HeadlessMcpDesktopTest { stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance"); stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load(); }); + connect(); + } + void connect() throws Exception { + connection = null; var initialize = request("initialize"); var params = initialize.putObject("params").put("protocolVersion", "2025-06-18"); params.putObject("capabilities"); params.putObject("clientInfo").put("name", "real-loop-test").put("version", "1"); @@ -92,6 +96,179 @@ class HeadlessMcpDesktopTest { assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "No managed runtime may survive the test"); } + void acquire() throws Exception { + fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire()); + task = value(call("studio_control_acquire", args())).path("taskId").asText(); + } + void prepareLongRun() throws Exception { + // Real guest work below the watchdog budget makes a 600-frame call observable in flight. + Files.writeString(source, Files.readString(source).replace("fn frame() -> void {", + "fn frame() -> void { let spin: int = 0; while (spin < 10000) { spin = spin + 1; }")); + acquire(); build("long-build"); boot(); + } + JsonNode startRunning(String requestId) throws Exception { + var receipt = value(call("studio_headless_advance", args().put("clientRequestId", requestId).put("frames", 600))); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + do { + var status = value(call("studio_operation_get", args().put("clientRequestId", requestId))); + assertFalse(status.path("workerTerminated").asBoolean(), status.toString()); + if (status.path("progress").path("completedFrames").asInt() > 0) return receipt; + Thread.sleep(5); + } while (System.nanoTime() < deadline); + throw new AssertionError("No runtime progress"); + } + @Test void disconnectAndDuplicateReceiptDoNotReplayAndCancellationRetainsTask() throws Exception { + prepareLongRun(); + var receipt = startRunning("cancel-me"); + var delete = HttpRequest.newBuilder(server.connection().endpoint()).DELETE() + .header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", connection).build(); + assertEquals(200, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode()); + client.close(); client = HttpClient.newHttpClient(); connect(); + assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); + assertEquals(receipt.path("operationId"), value(call("studio_headless_advance", + args().put("clientRequestId", "cancel-me").put("frames", 600))).path("operationId")); + value(call("studio_operation_cancel", args().put("operationId", receipt.path("operationId").asText()))); + var result = value(completed("cancel-me")); + assertEquals("CANCELLED", result.path("result").path("status").asText(), result.toString()); + assertTrue(result.path("progress").path("completedFrames").asInt() < 600); + assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); + assertEquals(session, value(call("studio_headless_state", args())).path("sessionId").asText()); + assertArrayEquals(png(call("studio_operation_get", args().put("clientRequestId", "cancel-me"))), project.automation().snapshot().capture().png()); + } + + @Test void revokeWaitsForRuntimeAndDocumentRefreshAndRejectsLateCalls() throws Exception { + prepareLongRun(); + value(call("studio_headless_advance", args().put("clientRequestId", "before-revoke").put("frames", 1))); + completed("before-revoke"); + var lastCapture = project.automation().snapshot().capture(); + var refreshEntered = new CompletableFuture(); var refreshGate = new CompletableFuture(); + var refreshed = new java.util.concurrent.atomic.AtomicReference(); + var handoff = project.automation().registerDocuments(new DocumentHandoff() { + public CompletionStage hasUnsavedChanges() { return CompletableFuture.completedFuture(false); } + public CompletionStage saveAll() { throw new AssertionError("Do not write old buffers"); } + public CompletionStage refreshFromDisk() { + assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "Runtime must stop before refresh"); + refreshEntered.complete(null); + return refreshGate.thenRun(() -> { try { refreshed.set(Files.readString(source)); } catch (Exception failure) { throw new RuntimeException(failure); } }); + } + }); + try { + String edited = Files.readString(source) + "\n// external edit retained on revoke\n"; Files.writeString(source, edited); + startRunning("revoked"); + fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire()); + refreshEntered.get(10, TimeUnit.SECONDS); + assertEquals(ControlState.RETURNING_CONTROL, project.automation().snapshot().state()); + assertFalse(project.automation().snapshot().manualAllowed()); + assertEquals("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "revoked")).path("structuredContent").path("error").path("code").asText()); + assertSame(lastCapture, project.automation().snapshot().capture(), "Revoked work must not publish a late frame"); + refreshGate.complete(null); + assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); + assertEquals(edited, refreshed.get()); assertEquals(edited, Files.readString(source)); + assertStale(true); + } finally { refreshGate.complete(null); handoff.close(); } + } + + @Test void waitingRevokeProjectCloseAndReopenNeverRestoreAuthority() throws Exception { + fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire()); + fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire()); + assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); + assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText()); + prepareLongRun(); startRunning("close-project"); + fx(dev::unLoad); + assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state(), "DEV does not own task lifetime"); + project.close(); + assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive)); + assertEquals("PROJECT_NOT_OPEN", call("studio_operation_get", args().put("clientRequestId", "close-project")).path("structuredContent").path("error").path("code").asText()); + project = app.getBean(ProjectSessionFactory.class).open(project.projectReference()); + assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); + assertEquals("INVALID_TASK", call("studio_build_start", args().put("clientRequestId", "late")).path("structuredContent").path("error").path("code").asText()); + } + + @Test void applicationContextShutdownClosesActiveProjectAndRuntime() throws Exception { + prepareLongRun(); startRunning("close-app"); + app.close(); + assertTrue(project.automation().snapshot().closed()); + assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive)); + assertFalse(server.isRunning()); + } + + @Test void nonresponsiveOwnedHostIsKilledAndHumanCanRetryReclaim() throws Exception { + prepareLongRun(); startRunning("frozen"); + var child = owned.stream().filter(p -> p.info().command().orElse("").endsWith("prometeu-headless")).findFirst().orElseThrow(); + // POSIX desktop gate: freeze only this test's observed child, never a discovered user process. + assertEquals(0, new ProcessBuilder("/bin/kill", "-STOP", Long.toString(child.pid())).start().waitFor()); + var outcome = project.automation().reclaim().toCompletableFuture().get(12, TimeUnit.SECONDS); + assertEquals(ControlResult.Status.CLEANUP_FAILED, outcome.status()); + assertFalse(project.automation().snapshot().manualAllowed()); + assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive)); + assertTrue(project.automation().reclaim().toCompletableFuture().get(5, TimeUnit.SECONDS).success()); + assertTrue(project.automation().snapshot().manualAllowed()); + } + + @Test void realManualDebugStillRunsAfterAgentReleaseAndBlocksNewGrant() throws Exception { + // The existing manual protocol owns port 7777. Do not connect to someone else's Debug. + try (var probe = new java.net.ServerSocket()) { probe.bind(new java.net.InetSocketAddress("127.0.0.1", 7777)); } + acquire(); build("before-debug"); boot(); + value(call("studio_control_release", args())); + try (var debug = app.getBean(p.studio.api.execution.ExecutionControllerFactory.class) + .create(project.projectReference(), project.projectLocalStudioSetup(), project.executionSession())) { + var running = debug.play().completion().toCompletableFuture().get(15, TimeUnit.SECONDS); + assertEquals(p.studio.api.execution.ExecutionState.RUNNING, running.state(), running.toString()); + ProcessHandle.current().descendants().filter(p -> p.info().command().orElse("").startsWith(installation + "/")).forEach(owned::add); + assertEquals(ControlResult.Status.BUSY, project.automation().grant(false).toCompletableFuture().get(2, TimeUnit.SECONDS).status()); + debug.stop(); + assertEquals(p.studio.api.execution.ExecutionState.STOPPED, project.executionSession().snapshot().state()); + } + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(7); + while ((!project.automation().snapshot().canGrant() || owned.stream().anyMatch(ProcessHandle::isAlive)) && System.nanoTime() < deadline) Thread.sleep(10); + assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive)); + assertTrue(project.automation().grant(false).toCompletableFuture().get(3, TimeUnit.SECONDS).success()); + assertTrue(project.automation().reclaim().toCompletableFuture().get(3, TimeUnit.SECONDS).success()); + } + + @Test void forcedHostLossPreservesKnownProgressAndRequiresExplicitNewSession() throws Exception { + prepareLongRun(); startRunning("crash"); + var child = owned.stream().filter(p -> p.info().command().orElse("").endsWith("prometeu-headless")).findFirst().orElseThrow(); + assertTrue(child.destroyForcibly()); child.onExit().get(5, TimeUnit.SECONDS); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + JsonNode result; + do { result = value(call("studio_operation_get", args().put("clientRequestId", "crash"))); if (result.path("workerTerminated").asBoolean()) break; Thread.sleep(5); } + while (System.nanoTime() < deadline); + assertTrue(result.path("workerTerminated").asBoolean()); + assertEquals("INFRASTRUCTURE_FAILURE", result.path("failure").path("code").asText()); + assertTrue(result.path("progress").path("completedFrames").asInt() < 600); + assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); + assertEquals(result.path("operationId"), value(call("studio_headless_advance", args().put("clientRequestId", "crash").put("frames", 600))).path("operationId")); + value(call("studio_headless_shutdown", args())); String previous = session; boot(); assertNotEquals(previous, session); + value(call("studio_headless_advance", args().put("clientRequestId", "after-crash").put("frames", 1))); + assertEquals("SUCCEEDED", value(completed("after-crash")).path("result").path("status").asText()); + } + + @Test void compileErrorAndGuestFaultCanBeCorrectedThroughHttpWithinTheSameTask() throws Exception { + acquire(); String identity = task; String original = Files.readString(source); + build("good"); boot(); + Files.writeString(source, "fn frame( {"); + var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString()); + assertFalse(value(call("studio_language_query", query)).path("result").isEmpty()); + value(call("studio_build_start", args().put("clientRequestId", "invalid"))); + var failed = value(completed("invalid")).path("result"); + assertEquals("FAILED", failed.path("status").asText()); assertFalse(failed.path("diagnostics").isEmpty()); + assertEquals(identity, project.automation().snapshot().task().value()); + Files.writeString(source, original.replace("x = x + 1;", "x = x / (x - x);")); + build("guest-fault"); boot(); + value(call("studio_headless_advance", args().put("clientRequestId", "faulted").put("frames", 3))); + var fault = value(completed("faulted")).path("result"); + assertEquals("GUEST_FAULT", fault.path("status").asText()); assertFalse(fault.path("diagnostics").isEmpty()); + assertFalse(value(call("studio_headless_fault", args())).path("fault").isNull()); + assertEquals(identity, project.automation().snapshot().task().value()); + Files.writeString(source, original); assertTrue(value(call("studio_language_query", query)).path("result").isEmpty()); + build("corrected"); boot(); + value(call("studio_headless_advance", args().put("clientRequestId", "corrected-run").put("frames", 3))); + assertEquals("SUCCEEDED", value(completed("corrected-run")).path("result").path("status").asText()); + assertEquals(identity, project.automation().snapshot().task().value()); + value(call("studio_control_release", args())); assertTrue(project.automation().snapshot().manualAllowed()); + } + @Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception { assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size()); assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs")); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java index f5f5f7fc..3507bfb1 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java @@ -82,6 +82,7 @@ class HeadlessProcessSessionTest { assertThrows(ExecutionException.class, () -> session.shutdown().toCompletableFuture().get(4, TimeUnit.SECONDS)); assertFalse(session.alive()); assertFalse(ProcessHandle.of(child).map(ProcessHandle::isAlive).orElse(false)); assertTrue(unrelated.isAlive()); + session.shutdown().toCompletableFuture().get(2, TimeUnit.SECONDS); // Explicit cleanup retry can acknowledge the dead tree. } finally { unrelated.destroyForcibly(); unrelated.waitFor(2, TimeUnit.SECONDS); } } @Test void missingConfiguredInstallationIsExplicitAndNeverDiscoversAnotherRuntime() throws Exception { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index 4d4e76dd..fbeb88f7 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -9,7 +9,9 @@ import p.studio.core.project.ProjectLocalStudioStateStore; import java.util.Objects; -public final class DefaultProjectSessionFactory implements ProjectSessionFactory { +public final class DefaultProjectSessionFactory implements ProjectSessionFactory, AutoCloseable { + private final java.util.Set sessions = new java.util.HashSet<>(); + private boolean closed; private final ProjectLocalStudioStateStore stateStore; private final ProjectLocalStudioSetupStore setupStore; private final LspLifecyclePort lsp; @@ -27,7 +29,8 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory } @Override - public ProjectSession open(ProjectReference projectReference) { + public synchronized ProjectSession open(ProjectReference projectReference) { + if (closed) throw new IllegalStateException("Project sessions are closing"); final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference"); final var setup = setupStore.load(project); final var state = stateStore.load(project); @@ -38,6 +41,23 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory try { lsp.boot(project); } catch (RuntimeException failure) { registration.unsubscribe(); throw failure; } ready.set(true); - return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, registration); + var session = new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, () -> { + registration.unsubscribe(); + synchronized (DefaultProjectSessionFactory.this) { sessions.removeIf(s -> s.automation() == automation); } + }); + sessions.add(session); + return session; + } + + /** Application teardown must stop projects before their executors and LSP dependencies. */ + @Override public void close() { + final java.util.List owned; + synchronized (this) { closed = true; owned = java.util.List.copyOf(sessions); } + RuntimeException failure = null; + for (var session : owned) { + try { session.close(); } + catch (RuntimeException error) { if (failure == null) failure = error; else failure.addSuppressed(error); } + } + if (failure != null) throw failure; } } diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java index 864b04fc..93ad9f8b 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java @@ -58,6 +58,36 @@ final class DefaultProjectSessionTest { return new ProjectReference("Example", "1.0.0", "pbs", 1, ProjectTarget.Game, temporaryDirectory); } + @Test void factoryTeardownClosesEveryOwnedSessionAndRejectsNewOpens() throws Exception { + var mapper = new ObjectMapper(); var lsp = new RecordingLsp(); + var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), + new ProjectLocalStudioSetupStore(mapper), lsp, new p.studio.core.project.ProjectAccessRegistry(), + new p.studio.core.support.ControlledOperations()); + var first = factory.open(project()); + var other = new ProjectReference("Other", "1", "pbs", 1, ProjectTarget.Game, + java.nio.file.Files.createDirectory(temporaryDirectory.resolve("other"))); + var second = factory.open(other); + first.automation().grant(false).toCompletableFuture().join(); first.automation().acquire(); + second.automation().grant(false).toCompletableFuture().join(); + factory.close(); factory.close(); + assertTrue(first.automation().snapshot().closed()); assertTrue(second.automation().snapshot().closed()); + assertEquals(2, lsp.shutdowns); + assertThrows(IllegalStateException.class, () -> factory.open(project())); + } + + @Test void factoryTeardownAttemptsOtherProjectsEvenWhenOneCloseFails() throws Exception { + var mapper = new ObjectMapper(); var lsp = new RecordingLsp(); lsp.failShutdown = true; + var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), + new ProjectLocalStudioSetupStore(mapper), lsp, new p.studio.core.project.ProjectAccessRegistry(), + new p.studio.core.support.ControlledOperations()); + factory.open(project()); + factory.open(new ProjectReference("Other", "1", "pbs", 1, ProjectTarget.Game, + java.nio.file.Files.createDirectory(temporaryDirectory.resolve("other")))); + var failure = assertThrows(IllegalStateException.class, factory::close); + assertEquals(1, failure.getSuppressed().length); assertEquals(2, lsp.shutdowns); + factory.close(); + } + @Test void failedBootNeverPublishesAnOpenProjectAndRemovesItsRegistration() { var mapper = new ObjectMapper(); From 4c3597a2fb6f7f8db5db4ec6b53d8e1b671e185f Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 13:33:40 +0100 Subject: [PATCH 12/15] record external agent acceptance and packaging validation --- README.md | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 79707f09..e0ca6bb4 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,22 @@ remain the developer's responsibility. See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) for schemas, authorization, limits and delivery boundaries. +### Troubleshooting automation + +| Symptom | Action | +| --- | --- | +| Connection rejected after Studio restarts | Copy DEV's configuration again: the token and OS-assigned endpoint are session-local. Do not publish the token. | +| Acquisition rejected or project busy | Grant control in DEV first; stop manual Debug before granting. Query an existing operation instead of starting another; serialize headless calls. | +| `RUNTIME_UNAVAILABLE` or handshake incompatibility | Check the project's configured runtime installation and its packaged headless command. Studio does not download a substitute. | +| `NO_FRAME_AVAILABLE` | Advance at least one frame before requesting a capture. | +| Advance/page limit rejected | Respect advertised limits and use reference pagination. Runtime's default maximum is 600 frames per advance; requests are not silently clamped. | +| Unknown language or missing reference | Inspect project context and the declared manifest language; use only advertised capabilities/reference IDs. PBS is a creation default, not an unknown-language fallback. | +| Returning control reports cleanup failure | Stop the external client's direct editing separately, then retry DEV reclaim after owned-process cleanup. Do not bypass the lock or restore stale editor buffers. | + +Language and SDK references are bundled locally; reading them does not require a +compiler checkout or network download. SDK/external-library changes remain outside +the game-authoring task, even when a reference exposes a limitation. + The real headless process adapter and task-service composition can be verified using an extracted runtime distribution: @@ -110,8 +126,18 @@ are not considered fixed by the passing integration tests: fallback and Java/Kotlin target compatibility warnings in `buildSrc`. The targeted regression passes, but the toolchain/target alignment needs separate review. -Cross-platform desktop coverage and real external-client acceptance are remaining -validation boundaries, not confirmed product defects. +Cross-platform desktop coverage remains a validation boundary, not a confirmed +product defect. Desktop acceptance so far covers macOS ARM64 and Codex CLI only. + +The first real Codex CLI acceptance run exercised editing, LSP, build/pack, input, +1,110 frames, native MCP images and explicit release. The developer confirmed the +DEV result and successfully ran the edited game using manual Debug Play afterward. +Additional follow-ups from that run: clearer errors for oversized +reference pages, guidance for sequential headless queries after `BUSY`, and easier +discovery of framebuffer dimensions. Capture before the first completed frame +correctly returns `NO_FRAME_AVAILABLE`; it is not a runtime defect. Noninteractive +clients must also provide an approval path for MCP work calls; the acceptance used +Codex's approval review with a project-scoped workspace-write sandbox. ## Requirements From 546c6d1ee57b13c6230296645fd701ca8fe22b13 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 15:55:09 +0100 Subject: [PATCH 13/15] docs: consolidate Studio AI-first acceptance and lessons --- README.md | 3 + ...-shared-authority-and-headless-evidence.md | 303 ++++++++++++++++++ ...CP Tools and Project Knowledge Contract.md | 17 +- 3 files changed, 320 insertions(+), 3 deletions(-) create mode 100644 discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md diff --git a/README.md b/README.md index e0ca6bb4..35668f82 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,9 @@ correctly returns `NO_FRAME_AVAILABLE`; it is not a runtime defect. Noninteracti clients must also provide an approval path for MCP work calls; the acceptance used Codex's approval review with a project-scoped workspace-write sandbox. +The completed baseline's architecture, acceptance evidence and post-implementation +follow-ups are consolidated in [LSN-0076](discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md). + ## Requirements - JDK 21 or newer recommended for local development diff --git a/discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md b/discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md new file mode 100644 index 00000000..3eb8510c --- /dev/null +++ b/discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md @@ -0,0 +1,303 @@ +--- +id: LSN-0076 +ticket: studio-headless-runtime-ai-first +title: AI-first Studio Through Shared Authority and Headless Evidence +created: 2026-09-29 +tags: [studio, runtime, headless, ai, mcp, automation] +--- + +## Context + +Owner: **studio**, with runtime preparation in `../runtime` and language-owned PBS +documentation/LSP integration. DSC-0068, accepted DEC-0060 and PLN-0139 delivered +28 ordered steps: runtime (01–07), DEV/shared services (08–14), MCP (15–21), and +real integration/acceptance (22–28). Those workflow identifiers are historical +references; maintained contracts live in the specs linked below. + +The original headless host was an in-process runtime API. Studio's human Debug +was useful, but neither a public automation protocol nor a safe authority boundary +for another editor. The goal was an external coding agent able to learn PBS, +edit a game, build/run it, see its pixels and iterate while the developer watches. +A complete gameplay library or embedded AI chat was not a prerequisite. + +## Key Decisions + +### Separate ownership, not parallel implementations + +The external coding client owns conversation, model/provider, native file edits +and budget. Studio owns project authority, build orchestration, process supervision +and the shared observation model. Runtime owns execution and framebuffer semantics. +The language frontend/SDK owns its references; the existing project LSP owns semantic +queries. DEV and MCP consume the same neutral services. + +```text +External coding agent -- local MCP HTTP --> Studio API/Core <-- DEV (JavaFX) + | + compiler/packer + existing LSP + | + supervised runtime JSONL/stdio + | + canonical PNG + frame identity +``` + +The configured installation provides `prometeu headless --stdio`. UTF-8 JSONL is +versioned, bounded and protocol-only on stdout; logs belong on stderr. A process +contains one session, with no implicit conflicting-work queue. Handshake establishes +runtime/protocol versions, capabilities and effective limits. Human Debug keeps its +own host/protocol. API/Core do not depend on JavaFX, Spring, HTTP/MCP or wire DTOs. + +This avoids a provider adapter inside Studio and avoids automating the human debugger +as the execution API. The deliberate cost is an explicit process boundary and +reconfiguration of the external client after Studio restarts. + +### Connection, authority and operation receipts are different identities + +Authentication to loopback `/mcp` permits discovery/context/reference reads, not +editing authority. A human grants a specific project in DEV; acquisition then +returns a task identity. Manual Debug and agent work exclude each other in services, +not only through disabled UI buttons. Waiting for acquisition already blocks +conflicting manual work. A disconnected client does not release the project. + +An operation's `clientRequestId` deduplicates a build or advance within the task. +The same ID and parameters return the same operation; changing parameters fails. +Lookup recovers a lost receipt without replaying frames. These records are in-memory, +not a source journal or restart-recovery mechanism. Runtime wire correlation has +its own `requestId`; neither identity is a substitute for valid task authority. + +### Return is a cleanup barrier + +The sequence is: invalidate task authority → stop managed work/processes → refresh +open documents from saved files → enable manual control. A late result cannot publish +a new capture or restore authority. Closing only DEV does not end the task; closing +the project/app does. Reopening starts manual, never with recovered agent authority. + +Compile errors, guest faults and runtime loss remain distinct outcomes. The first +two permit correction within the same task. Runtime loss requires explicit session +replacement, not replay. Forced cleanup reports infrastructure failure first; a +later explicit reclaim may acknowledge success only after the process tree is dead. + +The adversarial gate exposed a real app-teardown gap: UI closure alone did not own +every project session. The project-session factory now tracks and closes sessions +before dependent executors/LSP are destroyed, attempts other sessions after a failure, +and rejects new opens once closure begins. Cancellation also tolerates a concurrent +writer/timer shutdown so that it cannot bypass cleanup waiting. + +### Direct edits require truthful boundaries + +The agent edits actual project files. No worktree, merge/apply stage, code rollback, +Git cleanliness gate or automatic commit is imposed. Studio offers save-all-and-grant +for its dirty buffers and refreshes from disk on return. External unsaved buffers, +concurrent native writes and Git discipline remain the developer's responsibility. +Revocation cannot stop an external process from writing files directly; the developer +must also stop that client. SDK/external libraries are readable, not editable by +the game task. Read-only semantic refactoring scopes are enforced by the adapter. + +### Pixels are evidence; metadata explains which evidence + +MCP returns the lossless canonical PNG as native image content, plus session/build, +logical frame, render FrameId, dimensions, stride and pixel format. DEV projects +the same capture, with an explicit stale label after edits/rebuild/session changes. +Logical frames and render frames are independent counters. Neither a hash nor a +desktop screenshot replaces framebuffer pixels. Captures do not travel through +temporary image files, and there is no continuous video requirement. + +Default bounds are 600 frames/advance, 64 KiB/command, 32 MiB/response including +image/envelope, 5 s handshake, 60 s call, and 5 s cancel/shutdown grace. Oversized +requests fail rather than clamp. Deadlines supervise processes, not simulated time. + +## Final Result and Acceptance Evidence + +All 28 plan steps completed on the tested platform. Production exposes 17 MCP +tools, live DEV configuration-copy, shared task authority, existing LSP/build, +indexed offline language references and the supervised real Rust headless host. +There is no production fake, embedded agent/chat, generic MCP editor/shell or +provider-specific runtime behavior. + +### Requirement-to-evidence map + +| Requirement and steps | Evidence retained in code or acceptance record | +| --- | --- | +| Runtime contract, commands, limits, determinism; 01–07 | Runtime `automation_process.rs`, headless tests, published request/response schemas and packaged-installation smoke | +| Neutral architecture; 08, 14, 15, 27 | Studio specs 9–11; architecture/Modulith tests, 17 passing cases in final full rerun | +| Grant/revoke, symmetric locks, dirty-buffer handoff; 09–14 | `DefaultAutomationSessionTest`, Core execution/session tests, `DevDesktopTest`, `DevWorkspaceProjectionTest` | +| HTTP authentication/Origin/restart and real config; 16, 21 | `LocalMcpServerTest`, `McpContractTest`, `McpConnectionGuideTest`; packaged restart rejects prior credential | +| Manifest context, unknown languages/versions, indexed offline docs; 17–18 | `CompilerProjectKnowledgeTest`, `CompilerProjectLanguageCatalogTest`, `InstalledKnowledgeTest` | +| Saved-source LSP and dependency navigation; 19 | `AutomationLspQueriesTest`, including `externalDependencyNavigationIsReadableButRefactoringIsReadOnly`; SDK limitation remains explicit below | +| Task operations, lost receipts, deduplication; 20–21 | `McpTaskToolsTest`, Core operation tests; reconnect/duplicate advance in real desktop HTTP gate | +| Real supervision/build/corrective iterations; 22–23 | `HeadlessProcessSessionTest`, `HeadlessInstalledRuntimeTest`, `HeadlessTaskIntegrationTest` | +| Runtime/MCP/DEV pixel and identity parity; 24 | `HeadlessMcpDesktopTest` + independent `DirectHeadlessOracle`; compare every ImageView pixel, PNG bytes, metadata, reset/fresh-session/rebuild | +| Interruption/cleanup/Debug regression; 25 | Nine real HTTP/runtime/DEV tests, including crash, forced shutdown, app close, stale-result rejection and real manual Debug; controlled document participant makes refresh barrier observable | +| Real coding client and human confirmation; 26 | Codex CLI 0.158.0 run described below; developer confirmed DEV and manual Debug Play | +| Full regression and distribution; 27 | Commands/counts below; installed references and two extracted-ZIP application lifecycle cycles | +| Final propagation and handoff; 28 | This lesson, updated spec 11 delivery boundary, README troubleshooting, CLI validation and housekeeping | + +### Real external-client example + +The developer granted control in `../ai-first-smoke` and copied the descriptor. +Codex CLI 0.158.0 used a fresh ephemeral session, only the configured Studio MCP, +project-root workspace-write isolation and its approval-review mechanism. Default +noninteractive approval policy initially blocked acquisition before any edit; the +retry retained sandboxing and did not bypass the human grant. The configured default +model was used; this record does not assert an independently verified model identity. +Credentials stayed out of versioned files and reports. + +The agent consulted language/SDK references, edited only `src/main.pbs`, queried +LSP, built/packed and consumed native MCP image blocks. It changed the bundled +16x16 orange rectangle to one-pixel/frame directional movement in a 480x270 frame, +with no idle movement, opposing directions canceled before clamping, and unchanged +colors. Both builds succeeded; diagnostics were empty; final guest fault was null. +The 77 MCP calls included rejected/recovered calls and 13 native image blocks. + +| Scenario | Logical frame / FrameId | Client-reported observed position | +| --- | --- | --- | +| Idle for 10 frames | 10 / 9 | (0,32) | +| Right 20; down 20 | 30 / 29; 50 / 49 | (20,32); (20,52) | +| Left 10; up 10 | 60 / 59; 70 / 69 | (10,52); (10,42) | +| Horizontal then vertical opposites, 10 each | 80 / 79; 90 / 89 | (10,42), unchanged | +| Right + down, 500 | 590 / 589 | (464,254), intact at bottom-right | +| All directions, 10 | 600 / 599 | (464,254), unchanged at edge | +| Left + up, 500; idle 10 | 1100 / 1099; 1110 / 1109 | (0,0), intact at top-left | + +Build ID: `da441f65-479b-4099-8b86-fe48c7750e76`; runtime session: +`aa089209ec22c9a07286e5b01e967a57`. Frame identities/statuses were checked in tool +evidence; positions are the coding client's visual observations, not an invented +independent pixel measurement. Step 24 separately supplies exhaustive pixel parity. +Release returned MANUAL, no headless host remained, and game edits were preserved. +The developer confirmed the DEV result and successfully played the game through +normal Debug afterward. No game commit was made automatically. + +### Builds, commands and scope + +Studio executable code was `e6a83c94`; acceptance/troubleshooting documentation +was committed as `4c3597a2`. Runtime is merged at `01fab56`, distribution 0.1.0, +protocol 1.0. Native acceptance was **macOS ARM64 only**; no other coding client, +operating system or native-installer matrix is claimed. + +Studio final commands: + +```sh +./gradlew test build :prometeu-app:installDist --max-workers=2 --console=plain +./gradlew test :prometeu-app:installedKnowledgeTest :prometeu-app:headlessProcessTest --rerun-tasks -PstudioRuntimeInstall=/absolute/path/to/runtime --max-workers=2 --console=plain +``` + +The forced rerun executed all 91 tasks: normal suite **803 passed, 15 pre-existing +disabled tests, zero failures/errors**; installed knowledge **1 passed**; real +headless integration **4 passed**. The disabled compiler classes were +`IRVMIntrinsicRegistryParityTest`, `BackendGateIIntegrationTest` and +`MainProjectPipelineIntegrationTest`; none was disabled for this delivery. +The earlier step 25 targeted run had **254 passing tests**, including 9 real +HTTP/runtime/DEV and 4 DEV/Debug desktop tests. These overlap the full suite and +must not be added together as unique tests. + +The Studio ZIP was extracted outside the checkout. A test-only JavaFX probe loaded +only its distribution JARs, delegated to the real App init/start/stop, used isolated +preferences, and passed two shown-launcher/closed-listener cycles, credential +renewal and old-token rejection. It did not operate the developer's open window. +ZIP SHA-256: `256f80b25416c284dca58e5519fdde0be36e9a6a2a450cb58f9c453862188c8d`. + +Runtime final commands (cwd `../runtime`, separate temporary Cargo target): + +```sh +cargo test --workspace --offline --quiet +PROMETEU_PROTOCOL_TEST_INSTALL=/absolute/path/to/runtime cargo test -p prometeu-cli --offline --test automation_process -- --include-ignored +cargo test -p prometeu-host-desktop-winit --offline --lib -- --ignored +``` + +Workspace **678 passed**, with six opt-in tests ignored there; separate runs passed +all **13** process/protocol cases including the installed package, and all **5** +localhost Debug cases. Twelve process cases overlap the workspace result. The +runtime package was built during preparatory delivery; the final gate reused and +validated it rather than claiming a fresh distribution build. Installed headless +SHA-256: `24b74712397545ddd7f745daded859c12d19102f81c5b51bf46c202fb8d6b65d`. + +## Deferred Findings — Return Here After Implementation + +The user requested deferred investigation, not silent removal of these findings. + +| Finding | Owner and next investigation | +| --- | --- | +| `Input.pad()` SDK definition returns no location | Investigated on 2026-09-29: editorial lookup succeeds, but the physical-file policy filters the virtual SDK source. A separate chained-call editorial limitation was reproduced; see below. No runtime defect or fix is claimed. | +| Oversized reference page produces generic `-32602` | Studio MCP: improve parameter-limit discoverability/error specificity; default pagination already works. | +| Concurrent capture/fault/state may return BUSY | Studio MCP/Core: review concurrency guidance and clarity. Sequential calls work; do not weaken accepted exclusivity implicitly. | +| Framebuffer dimensions were discovered from capture | Language/runtime documentation: improve discovery; this does not prove dimensions are absent from every reference. | +| JDK 25/Kotlin target-24 fallback, JavaFX module/native-access/Unsafe warnings | Build/desktop tooling: review supported toolchain alignment and startup options separately. Passing tests do not erase warnings. | +| UI automation helper required newer Node than 22.13.1 | Environment tooling, not Studio: upgrade only as separate authorized work; human DEV confirmation supplied acceptance. | +| macOS ARM64 + Codex is the validated matrix | Future interoperability/platform testing; no uniform Grok/Windows/Linux promise. | + +`NO_FRAME_AVAILABLE` before the first completed frame and client permission prompts +are expected boundaries, not guest defects. The shutdown ownership/reclaim bugs +found during step 25 are fixed and tested, not outstanding issues. + +### Follow-up Investigation: SDK Navigation and Chained Calls + +Owner: `compiler/pbs`, with propagation to compiler tooling contracts and Studio/LSP +consumers. This diagnosis does not reopen the completed AI-first delivery or change +its accepted requirements. + +On 2026-09-29, a temporary Java probe exercised `CompilerLanguageServiceBridge` +with a request-local PBS overlay on `test-projects/main/src/main.pbs`, using the +application runtime classpath. It compared raw PBS editorial locations, exported +frontend locations, final LSP definitions, and hover. No production source was +changed. The comparison included imports from `@sdk:input` and `@sdk:gfx`, a local +`helper()`, an explicitly typed `pad: InputPad`, and `button: InputButton`. + +| Cursor target | Raw PBS locations | Frontend / LSP locations | Hover | +| --- | --- | --- | --- | +| Local `helper()` | 1 | 1 / 1 | Resolved | +| `pad` in `Input.pad()` | 1 | 0 / 0 | `pad() -> InputPad` | +| `left` in `pad.left()` | 1 | 0 / 0 | `left() -> InputButton` | +| `down` in `button.down()` | 1 | 0 / 0 | `down() -> bool` | +| `down` in `pad.left().down()` | 0 | 0 / 0 | No symbol information | +| `left` and `down` in `Input.pad().left().down()` | 0 each | 0 / 0 each | No symbol information | +| `clear` in `Gfx.clear(0)` | 1 | 0 / 0 | Resolved | + +There are two separate causes: + +1. **SDK destination policy, not failed lookup.** `InterfaceModuleLoader` registers + SDK declarations under `/virtual/stdlib/sdk/input/main.pbs` (and the corresponding + `gfx` path). The source handle can read the declaration text, but the path is not + a physical file. `PBSFrontendLanguageService.toFrontendLocation` explicitly + rejects it via `Files.isRegularFile`. The LSP bridge also reads destination text + from disk; removing the frontend check alone would not deliver a usable target. + This behavior follows Compiler Spec 23 §8.3 and the physical-file rule preserved + in `LSN-0068`, and already has an explicit `Gfx.clear()` regression assertion in + `CompilerLanguageServiceBridgeTest.definitionUsesEditorialLookupAndPhysicalStdlibFiles`. +2. **Chained-call editorial receiver resolution.** + `PbsEditorialSupportService.resolveReceiverTypeBeforeDot` uses + `resolveChainSegmentsEndingAt`, which walks identifier/dot chains, not a call + expression ending in `)`. Thus the receiver of `down` in `pad.left().down()` is + unknown before destination mapping even begins. An explicitly typed intermediate + `button` restores raw lookup and hover, while the virtual-source policy still + prevents navigation. This is an editorial limitation, not evidence that executing + the same expression fails. + +Recommended follow-up, not an accepted implementation decision: address chained +receiver resolution in the PBS editorial layer, and separately decide how to expose +the exact SDK sources as navigable read-only files. A version-scoped physical source +cache is compatible with the existing destination policy; virtual-document support +would require an explicit contract revision. Neither approach should duplicate SDK +semantics in MCP, permit SDK edits, or point to an unrelated developer checkout. + +## Pitfalls and Takeaways + +- A successful HTTP fixture is not an external-agent acceptance test. Prove both. +- Tab disposal is not task disposal; application teardown must own hidden sessions. +- Never unlock before process termination and document refresh acknowledge completion. +- Do not replay an advance because a connection or receipt was lost. +- A matching hash/blank canvas is weak visual evidence. Compare actual pixels, + metadata and an input timeline that changes a known object. +- An empty SDK definition is a language limitation, not permission to edit SDK code. +- Packaging language knowledge is part of making an unfamiliar language usable by + agents; adding another hidden language configuration is not. +- Keep provider permissions separate from Studio authority. Neither bypasses the other. +- Preserve explicit platform/client/test exclusions and deferred findings at closure. + +## References + +- Historical accepted decision DEC-0060 and completed plan PLN-0139, DSC-0068. +- [Studio architecture](../../../docs/specs/studio/9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md). +- [DEV and authority contract](../../../docs/specs/studio/10.%20DEV%20and%20Automation%20Specification.md). +- [MCP tools and knowledge contract](../../../docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md). +- [Usage and troubleshooting](../../../README.md#external-coding-agents-mcp). +- Runtime-owned contract: `../runtime/docs/specs/runtime/11a-headless-automation-protocol.md`. +- Previous foundation: [Services must outlive UI](../DSC-0067-studio-core-javafx-decoupling/LSN-0075-studio-services-must-outlive-the-current-ui.md). 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 02e8d663..c9adcc31 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 @@ -479,6 +479,17 @@ The normal desktop Debug process starts after release and blocks a new grant. The suspension/manual-Debug scenarios require a POSIX desktop and a free Debug port 7777; the gate never attaches to an existing user's Debug process. -The automated client is not an external coding agent. Real-agent compatibility -and final packaging acceptance remain later gates. API/Core and JavaFX MUST NOT -import MCP/HTTP implementations; architecture tests enforce it. +The automated client is not an external coding agent. Separate acceptance on +2026-09-29 used Codex CLI 0.158.0 against the packaged Studio and runtime 0.1.0 +on macOS ARM64. The agent consulted references/LSP, edited saved PBS source, +built/packed, consumed native MCP PNGs, tested 1,110 frames of directional input, +and explicitly released authority. The developer confirmed DEV and then ran the +edited game through manual Debug Play. This establishes compatibility for that +client/platform, not uniform compatibility across providers or operating systems. + +Full regression and distribution gates also passed: installed offline references, +real runtime protocol tests, architecture/Modulith, and two isolated startup/stop +cycles using the extracted Studio ZIP. The latter verified listener closure and +old-credential rejection after restart. API/Core and JavaFX MUST NOT import +MCP/HTTP implementations; architecture tests enforce it. Consolidated acceptance +evidence and deferred findings live in the DSC-0068 lesson, not in temporary logs. From 73aaeb08323f0b059f4b862f6985b3de5b71ed51 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 16:14:21 +0100 Subject: [PATCH 14/15] fix: synchronize automation termination and stabilize headless tests --- .../p/studio/app/runtime/HeadlessFixture.java | 12 +++- .../runtime/HeadlessProcessSessionTest.java | 7 +- .../core/language/TaskLanguageQueries.java | 7 +- .../session/DefaultAutomationSession.java | 14 +++- .../language/TaskLanguageQueriesTest.java | 64 +++++++++++++++++++ .../session/DefaultAutomationSessionTest.java | 12 ++++ 6 files changed, 105 insertions(+), 11 deletions(-) create mode 100644 prometeu-studio-core/src/test/java/p/studio/core/language/TaskLanguageQueriesTest.java diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java index 21a5ea7f..d6e91e54 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java @@ -9,8 +9,14 @@ import java.util.*; /** Deliberately adversarial child process. Never packaged into production. */ public final class HeadlessFixture { static final ObjectMapper MAPPER = new ObjectMapper(); - // Allow normal JVM startup under load; call/cancel deadlines remain deliberately short. - static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 5000, 500, 150); + // Successful JVM/ImageIO startup and fragmented IO need headroom on CI. Only + // fixtures that deliberately hang use short call or shutdown deadlines. + static HeadlessLimits limits(String mode) { + boolean hungCall = mode.equals("hang-call") || mode.equals("hang-cancel"); + boolean hungShutdown = hungCall || mode.equals("descendant"); + return new HeadlessLimits(600, 4096, 4096, 5000, + hungCall ? 500 : 5000, hungShutdown ? 150 : 2000); + } static String mode; static void emit(JsonNode value) throws Exception { byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8); @@ -30,7 +36,7 @@ public final class HeadlessFixture { 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)); - hello.set("limits", MAPPER.valueToTree(LIMITS)); + 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); if (mode.equals("descendant")) { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java index 3507bfb1..c36454ad 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java @@ -12,11 +12,10 @@ import static org.junit.jupiter.api.Assertions.*; class HeadlessProcessSessionTest { @TempDir Path root; - static final HeadlessLimits LIMITS = HeadlessFixture.LIMITS; final List sessions = new ArrayList<>(); HeadlessProcessSession start(String mode) throws Exception { var process = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), mode).directory(root.toFile()).start(); - var session = new HeadlessProcessSession(process, new ObjectMapper(), LIMITS, "build"); sessions.add(session); return session; + var session = new HeadlessProcessSession(process, new ObjectMapper(), HeadlessFixture.limits(mode), "build"); sessions.add(session); return session; } @AfterEach void cleanup() { sessions.forEach(session -> session.abort("test cleanup")); } @Test void fragmentedProtocolPreservesUnsignedFrameIdentityLayoutAndSeparateStderr() throws Exception { @@ -58,11 +57,11 @@ class HeadlessProcessSessionTest { var entered = new CountDownLatch(1); try (var workers = Executors.newSingleThreadExecutor()) { var result = workers.submit(() -> session.advance(30, ignored -> entered.countDown())); - assertTrue(entered.await(2, TimeUnit.SECONDS)); + assertTrue(entered.await(5, TimeUnit.SECONDS)); assertEquals(AutomationFailure.Code.BUSY, assertThrows(AutomationException.class, () -> session.call(TaskTools.HeadlessAction.STATE, Map.of())).failure().code()); session.cancel(); - var outcome = result.get(2, TimeUnit.SECONDS); + var outcome = result.get(10, TimeUnit.SECONDS); assertEquals(AutomationOutcome.Kind.CANCELLED, outcome.kind()); assertEquals(2, outcome.completedFrames()); assertNotNull(outcome.capture()); } session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.alive()); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java b/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java index 01b4cd9e..1166787e 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/language/TaskLanguageQueries.java @@ -30,8 +30,11 @@ public final class TaskLanguageQueries implements LanguageQueries { 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); + // A failed result must also wait for worker termination and admission + // cleanup before the caller can issue its next query. + handle.completion().handle((outcome, failure) -> null) + .thenCompose(ignored -> handle.termination()).toCompletableFuture().get(12, TimeUnit.SECONDS); + handle.completion().toCompletableFuture().get(); requireTask(session, taskId); return Objects.requireNonNull(result.get()); } catch (ExecutionException failure) { 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 b1bd6134..ca19bbc5 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 @@ -236,11 +236,21 @@ public final class DefaultAutomationSession implements AutomationSession { publish(); } }); - operation.termination().whenComplete((v, f) -> { + var settled = operation.termination().whenComplete((v, f) -> { subscription.unsubscribe(); synchronized (this) { if (active == operation) { busy = false; publish(); } } }); - publish(); return operation; + // Waiting on the raw worker future does not wait for its dependent + // callbacks. Expose the stage that also releases session admission. + var handle = new OperationHandle() { + @Override public OperationId id() { return operation.id(); } + @Override public OperationSnapshot snapshot() { return operation.snapshot(); } + @Override public CompletionStage completion() { return operation.completion(); } + @Override public CompletionStage termination() { return settled; } + @Override public boolean cancel() { return operation.cancel(); } + @Override public OperationSubscription subscribe(Consumer observer) { return operation.subscribe(observer); } + }; + publish(); return handle; } @Override public synchronized void attachRuntime(TaskIdentity identity, ManagedHeadlessSession next) { diff --git a/prometeu-studio-core/src/test/java/p/studio/core/language/TaskLanguageQueriesTest.java b/prometeu-studio-core/src/test/java/p/studio/core/language/TaskLanguageQueriesTest.java new file mode 100644 index 00000000..431331e3 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/language/TaskLanguageQueriesTest.java @@ -0,0 +1,64 @@ +package p.studio.core.language; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.api.operation.*; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.core.support.ControlledOperations; + +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.*; + +import static org.junit.jupiter.api.Assertions.*; + +class TaskLanguageQueriesTest { + @TempDir Path root; + + @Test void failedQueryWaitsForTerminationBeforeReturningAndAcceptingTheNextQuery() throws Exception { + var operations = new ControlledOperations(); + var submitted = new LinkedBlockingQueue>(); + var executor = new OperationExecutor() { + @Override public OperationHandle submit(String summary, Callable work) { + var handle = operations.submit(summary, work); + submitted.add(operations.last); + return handle; + } + }; + var session = new DefaultAutomationSession(root, executor); + var projects = new ProjectAccessRegistry(); + var registration = projects.register(root, session::enterManual, () -> true, session); + var queries = new TaskLanguageQueries(projects, new LanguageQueryPort() { + @Override public Map query(TaskIdentity task, String operation, Map parameters) { + return Map.of("operation", operation); + } + @Override public void endTask(TaskIdentity task) { } + }); + assertTrue(session.grant(false).toCompletableFuture().join().success()); + var task = session.acquire().task(); + try (var caller = Executors.newSingleThreadExecutor()) { + var failed = caller.submit(() -> queries.query(root, task.value(), "formatting", Map.of())); + var worker = submitted.poll(5, TimeUnit.SECONDS); + assertNotNull(worker); + var failure = new AutomationException(AutomationFailure.Code.READ_ONLY_SCOPE, "Read-only dependency"); + worker.completed.completeExceptionally(failure); + try { + assertThrows(TimeoutException.class, () -> failed.get(100, TimeUnit.MILLISECONDS)); + assertEquals(ControlResult.Status.BUSY, assertThrows(ControlDeniedException.class, + () -> session.submit(task, "overlap", () -> null)).status()); + } finally { worker.stopped.complete(null); } + assertSame(failure, assertThrows(ExecutionException.class, () -> failed.get(5, TimeUnit.SECONDS)).getCause()); + var next = caller.submit(() -> queries.query(root, task.value(), "definition", Map.of())); + var nextWorker = submitted.poll(5, TimeUnit.SECONDS); + assertNotNull(nextWorker); + nextWorker.finish(); + assertEquals("definition", next.get(5, TimeUnit.SECONDS).get("operation")); + } finally { + if (operations.last != null) operations.last.stopped.complete(null); + session.closeAsync().toCompletableFuture().join(); + registration.unsubscribe(); + } + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java index a48470ae..155d07aa 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java @@ -18,6 +18,18 @@ class DefaultAutomationSessionTest { ControlResult await(CompletionStage result) { return result.toCompletableFuture().join(); } TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); } + @Test void terminationObserversCanSubmitTheNextOperation() { + var s = session(); var task = start(s); + var first = s.submit(task, "first", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null)); + var worker = operations.last; + var next = first.termination().thenRun(() -> s.submit(task, "next", + () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null))); + worker.finish(); + assertDoesNotThrow(() -> next.toCompletableFuture().join()); + operations.last.finish(); + assertEquals(RETURNED, await(s.release(task)).status()); + } + @Test void taskCleanupRunsAfterWorkerTerminationAndBeforeManualControl() { var s = session(); var task = start(s); var cleaned = new java.util.concurrent.atomic.AtomicInteger(); From 3f675ca0c968e04f76b01457d4e3e0e26f5e7f6a Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 16:33:36 +0100 Subject: [PATCH 15/15] test: separate LSP initialization and shutdown timeouts --- .../java/p/studio/lsp/services/LspServerLifecycleTest.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java index 9e8ba13d..f03f5114 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java @@ -8,6 +8,8 @@ import java.net.Socket; import static org.junit.jupiter.api.Assertions.*; class LspServerLifecycleTest { + private static final int INITIALIZATION_TIMEOUT_MS = 10_000; + private static final int SHUTDOWN_TIMEOUT_MS = 2_000; @TempDir Path temporary; @Test void projectEndpointsAreIndependentAndShutdownClosesConnectedSockets() throws Exception { @@ -21,12 +23,15 @@ class LspServerLifecycleTest { assertNotEquals(endpoint.port(), lifecycle.endpoint(second).orElseThrow().port()); assertTrue(lifecycle.endpoint(new LspProjectContext("first", "other-language", temporary)).isEmpty()); try (var socket = new Socket(endpoint.host(), endpoint.port())) { - socket.setSoTimeout(2000); + // Cold LSP/compiler initialization can be slower on a loaded CI worker. + // Keep its budget separate from the socket-closure assertion below. + socket.setSoTimeout(INITIALIZATION_TIMEOUT_MS); String request = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"rootUri\":\"" + temporary.toUri() + "\",\"capabilities\":{}}}"; byte[] body = request.getBytes(java.nio.charset.StandardCharsets.UTF_8); socket.getOutputStream().write(("Content-Length: " + body.length + "\r\n\r\n").getBytes(java.nio.charset.StandardCharsets.US_ASCII)); socket.getOutputStream().write(body); socket.getOutputStream().flush(); assertNotEquals(-1, socket.getInputStream().read()); + socket.setSoTimeout(SHUTDOWN_TIMEOUT_MS); lifecycle.shutdownServer(first); socket.getInputStream().readAllBytes(); // Buffered reply drains, then EOF; no abandoned client connection. assertTrue(lifecycle.endpoint(first).isEmpty());