Compare commits

..
Author SHA1 Message Date
bquarkz 13c0ababbb feat(pbs): align typed values and Pad input facade
Test / Build occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/pr-master There was a failure building this commit
Intrepid/Prometeu/Studio/pipeline/head There was a failure building this commit
2026-10-15 15:48:50 +01:00
bquarkz 603ed01227 feat(compiler): port runtime catalogs and enforce target ABI (AGD77)
Import both runtime catalogs and provenance, port all intrinsic metadata and exact constants, and validate target signatures and carriers through the common pipeline. Package matching compiler/SDK resources and add active parity plus production runtime conformance checks.

Validation: 420 compiler/PBS tests passed, with 12 existing skips; provider export, runtime execution and installed catalog checks passed. The pre-existing Gfx.clear typed-metadata failure remains active and assigned to AGD78 under the explicitly accepted scope revision recorded in LSN-0080.
2026-10-15 13:07:49 +01:00
bquarkz bd5694dbdf feat(compiler): implement typed registry and production PBX conformance (AGD76) 2026-10-14 21:04:04 +01:00
bquarkz a9ede541af Merge pull request 'feat(pbs): resolve editorial chains and expose read-only external sources' (#35) from dev/pbs-editorial-chains-sdk-navigation into master
Test / Build skipped: 16, passed: 942
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 66.91% (23371/34928) * Branch Coverage: 56.47% (9948/17616) * Lines of Code: 34928 * Cyclomatic Complexity: 15041 #### Quality Gates Summary Output truncated.
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #35
2026-10-07 08:36:18 +00:00
bquarkz d71e46ade8 fix(ci): publish coverage separately from test checks
Test / Build skipped: 16, passed: 838
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 66.91% (23370/34928) * Branch Coverage: 56.47% (9947/17616) * Lines of Code: 34928 * Cyclomatic Complexity: 15041 #### Quality Gates Summary Output truncated.
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
2026-10-07 09:25:14 +01:00
bquarkz 8dff6d8d5f package testing
Test / Build skipped: 16, passed: 838
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
2026-10-07 09:09:31 +01:00
bquarkz 967b9ec598 feat(pbs): resolve editorial chains and expose read-only external sources
Intrepid/Prometeu/Studio/pipeline/head Build started...
Test / Build skipped: 16, passed: 838
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
2026-10-07 09:00:31 +01:00
bquarkz d0737df0ac feat(studio): integrate project MCP setup and lifecycle
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
Test / Build skipped: 15, passed: 926
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
2026-09-29 19:24:28 +01:00
bquarkz 97cf5e1919 Merge branch 'dev/studio-headless-runtime-ai-first'
Test / Build skipped: 15, passed: 909
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
2026-09-29 16:42:37 +01:00
bquarkz 3f675ca0c9 test: separate LSP initialization and shutdown timeouts
Test / Build skipped: 15, passed: 805
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
2026-09-29 16:33:36 +01:00
bquarkz 73aaeb0832 fix: synchronize automation termination and stabilize headless tests
Test / Build occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/pr-master There was a failure building this commit
2026-09-29 16:14:21 +01:00
bquarkz 546c6d1ee5 docs: consolidate Studio AI-first acceptance and lessons
Test / Build occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/pr-master There was a failure building this commit
Intrepid/Prometeu/Studio/pipeline/head There was a failure building this commit
2026-09-29 15:55:09 +01:00
bquarkz 4c3597a2fb record external agent acceptance and packaging validation 2026-09-29 13:33:40 +01:00
bquarkz e6a83c94e0 verify automation interruption recovery and manual debug lifecycle 2026-09-29 12:06:48 +01:00
bquarkz 4f148a50de verify real MCP runtime and DEV framebuffer parity 2026-09-29 11:40:02 +01:00
bquarkz 379420e7a9 compose real headless runtime with task build and lifecycle 2026-09-29 11:27:42 +01:00
bquarkz bc76f08bbd implement real headless process gateway and supervision 2026-09-29 11:02:21 +01:00
bquarkz 9592c9b274 connect DEV to live MCP configuration and verify tool conformance 2026-09-29 10:36:50 +01:00
bquarkz 20bbbd26bd expose task control and deduplicated operations through MCP 2026-09-29 10:26:19 +01:00
bquarkz c1834bad1f connect MCP language queries to project LSP 2026-09-29 09:21:59 +01:00
bquarkz feb57c5298 package PBS references and expose paginated MCP reads 2026-09-29 08:48:33 +01:00
bquarkz 58f11a8123 expose manifest-driven project knowledge through MCP 2026-09-29 08:30:38 +01:00
bquarkz 9f61f9c07d add MCP tool contracts and authenticated local HTTP transport 2026-09-29 07:55:29 +01:00
bquarkz e3c3b2cbb7 implement DEV workspace and project automation authority 2026-09-29 07:09:37 +01:00
bquarkz 0ddf3ef70d Merge pull request 'dev/studio-core-javafx-decoupling' (#32) from dev/studio-core-javafx-decoupling into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 64.03% (20490/31999) * Branch Coverage: 54.25% (8244/15196) * Lines of Code: 31999 * Cyclomatic Complexity: 13164 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 819
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #32
2026-09-25 10:38:40 +00:00
289 changed files with 18975 additions and 1546 deletions
+185 -1
View File
@@ -21,14 +21,198 @@ The root project is a monorepo with these main areas:
## Current Product Shape ## Current Product Shape
The Studio shell currently organizes the product around three workspaces: The Studio shell currently organizes the product around four workspaces:
- Assets - Assets
- Debug - Debug
- DEV (external-agent authorization and observation)
- Shipper - 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. 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)
Studio includes its own `mcp --project <absolute-root>` mode. Configure the native
client once; project grants and desktop restarts no longer require copying ports
or tokens. The initial integration targets Codex on macOS.
1. Install/stage Studio with its bundled Java runtime (see below). New projects
prepare the local client entry during scaffolding. Opening an existing project
also prepares its enabled integration automatically; Studio starts the shared
MCP server itself. **DEV → Prepare assistant** retries preparation after resolving
a reported setup conflict. Opening a project does not grant agent control.
2. Open the coding client in the project directory. Trust the project and reload
MCP once if the client requests it. Studio does not alter client approval policy.
Tools can initialize/list even before the desktop is open or access is granted.
3. Open the project in Studio and grant control in DEV (save first if prompted).
Active Debug prevents granting. The connector discovers access automatically.
4. The agent acquires a task, consults project/language/SDK references, edits saved
project files with its native tools and validates through LSP/build. SDK and
external libraries remain read-only.
5. Recover uncertain operations by operationId/clientRequestId lookup within the
same task; never replay build/advance blindly. Explicitly release control when
done. Human reclaim also revokes access; stop direct external file edits separately.
The client invokes the same Studio artifact over stdio. It forwards to Studio's
project-scoped loopback service using protected, transient
`.studio/mcp/connection.json`. The permanent `.codex/config.toml` entry contains
installed Java/classpath/root arguments, not credentials. Both local outputs are
ignored by Git. Unrelated client settings are preserved; tracked or conflicting
Studio entries require deliberate resolution. `.studio/setup.json` preserves
neutral integration intent and existing runtime/editor settings.
After desktop restart, grant again in DEV. Keep the same client session and
configuration; old task identities and operation receipts are not restored.
DEV displays connection separately from project authority. No project-local
launcher, Python transport script or embedded chat is required.
### Reading external source code
VS Code F12 opens SDK/core and admitted libraries as read-only documents, with
hover, continued F12 and syntax highlighting. SDK/core stay bundled; no editorial
copies are created. After a source revision changes or a session ends, navigate
again instead of reusing old positions.
For MCP, use `studio_language_query` with `operation: "definition"`, then pass a
returned `prometeu-source:` URI to `operation: "readExternalSource"`. The response
contains `descriptor` and `text`; hover and definition accept the same URI within
the owning task. Another task cannot reuse it. MCP does not require VS Code open.
External or mixed edit proposals are refused in full. Library installation/cache
management is outside this feature. See the [extension guide](tools/vscode-extension/README.md).
### Installation and IntelliJ development
Build and stage the complete distribution, including its Java runtime:
```bash
./gradlew :prometeu-app:stageStudioInstallation
```
The macOS default is `~/Library/Application Support/Prometeu/Studio/current`.
Staging validates a new version before atomically changing `current`, retaining
older versions for rollback and running processes. Native client registration
uses absolute paths and argument arrays, independent of shell PATH:
```text
command: <installation>/current/runtime/bin/java
args: ["-cp", "<installation>/current/lib/*", "p.studio.app.StudioLauncher", "mcp", "--project", "<absolute-project-root>"]
```
For development, use an isolated installation:
```bash
./gradlew :prometeu-app:stageStudioInstallation -PstudioInstallationRoot=/absolute/dev-installation
```
In IntelliJ, run/debug `p.studio.app.StudioLauncher` with the `prometeu-app`
runtime classpath and VM option `-Dstudio.installationRoot=/absolute/dev-installation`.
The desktop and client-owned connector are separate JVMs. To debug the latter,
add the development-only VM argument
`-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005`
before `-cp` in the local MCP entry, restart that MCP process, then use IntelliJ's
**Remote JVM Debug** on localhost:5005. Do not commit this local configuration.
Because manual edits to the managed entry are protected, restore its original
content before using preparation again. Regular registration never enables JDWP.
The packaged automated gate checks bundled Java, upgrade/rollback, project paths
with spaces, minimal environment, scaffold/preparation and JavaFX startup:
```bash
./gradlew :prometeu-app:installedConnectorTest
```
The current production tools cover context, references, task control, LSP,
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.
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 |
| --- | --- |
| Waiting for access / desktop restarted | Open the project and grant again in DEV. Keep the existing client configuration. |
| Stale connection / incompatible catalog | Grant fresh access, or update the installed Studio when versions differ. Do not edit transient credentials. |
| Preparation conflict | Preserve the existing client settings; resolve a tracked/user-owned/edited Studio table explicitly, then prepare again. |
| 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:
```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 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.
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.
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:** the historical probe of the former `Input.pad()`
API returned no location; the current input API is `Pad`/`Button` and `Touch`. 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 remains a validation boundary, not a confirmed
product defect. Baseline HTTP desktop acceptance covers macOS ARM64 and Codex CLI only. The integrated stdio flow completed its separate acceptance gates through automated validation and user-confirmed native-client, graphical-launch and IntelliJ checks; see [LSN-0077](discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md) for evidence provenance.
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.
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 ## Requirements
- JDK 21 or newer recommended for local development - JDK 21 or newer recommended for local development
@@ -8,6 +8,14 @@ tags: [studio, lsp, vscode, compiler-pbs, editor, definition]
# PBS go-to-definition uses editorial lookup and physical files # PBS go-to-definition uses editorial lookup and physical files
> Historical policy: DEC-0062 / PLN-0141 explicitly superseded the physical-only
> definition restriction in October 2026. SDK/core and dependencies now use
> revision-bound read-only external documents for supporting clients. Compiler
> Spec 23 and Studio Spec 11 define the current contract. The original lesson below
> preserves the earlier decision; it must not be read as prohibiting today's
> external navigation. References, symbols, links and hierarchies retain their
> separately scoped contracts. See LSN-0078 for the implementation and pitfalls.
## Original Problem ## Original Problem
PBS editor assistance already had compiler-backed completion, hover, and signature help (`LSN-0051`). Users still could not jump from a use to a declaration. Wave 1 explicitly deferred `go to definition`. PBS editor assistance already had compiler-backed completion, hover, and signature help (`LSN-0051`). Users still could not jump from a use to a declaration. Wave 1 explicitly deferred `go to definition`.
@@ -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).
@@ -0,0 +1,190 @@
---
id: LSN-0078
ticket: pbs-editorial-chains-sdk-navigation
title: PBS chains and revision-bound external sources
created: 2026-10-07
tags: [compiler, compiler-pbs, lsp, studio, sdk, navigation]
---
# PBS chains and revision-bound external sources
Domain owner: `compiler/pbs`. Propagation: `compiler/general` and `studio`.
DEC-0062 and PLN-0141 were implemented together. This lesson preserves the outcome
and validation after their workflow artifacts are removed.
## Original problem
Compilation supported expressions such as `Input.pad().left().down()`, but the
editorial receiver scanner only understood identifier/dot sequences. Hover,
definition, completion and signature help therefore lost the receiver after a call.
Separately, definition discarded SDK/core handles because their bundled resources
had virtual paths rather than regular files. SDK hover could succeed while F12
returned nothing. These were independent defects requiring integrated acceptance.
A third regression fixture confirmed that source discovery skipped a dependency
explicitly admitted under `.workspace`: the crawler tested every ancestor of the
absolute path against ignored directory names.
## Consolidated decision
Keep language resolution in the frontend. Share receiver typing across the four
project queries, using PBS parsing and flow semantics. Support known-return call
chains, nested arguments, typed/inferred variables, parentheses and recoverable
partial code. Unknown or ambiguous receivers stay unresolved. This changes no
language rule, compiler/linker pipeline, ABI or runtime behavior.
Expose SDK/core and admitted dependency sources as read-only in-memory documents.
SDK/core remain bundled, without editorial extraction. Libraries remain their
existing physical sources; a library inside the project directory is still an
external owner. Dependency installation, download, cache management and its future
Studio UI remain DSC-0072 / AGD-0074.
Each external document binds content, byte ranges and frontend semantic context to
the same analyzed revision. The host emits an opaque project-session URI; the
content digest is not an SDK version. VS Code and MCP share that source and
semantic authority. They do not implement another PBS resolver.
All proposals touching external sources are refused as a whole. Normal project
editing remains available. References, workspace symbols, links and hierarchies
retain their earlier physical scopes. External definition does not expand them.
## Final implementation
1. `PbsParser.parseExpression` exposes the existing expression grammar for complete
receiver fragments. `PbsEditorialSupportService` locates a fragment boundary and
delegates its type to `PbsFlowExpressionAnalyzer`. The same path serves all four
project queries, including trailing dots and unfinished arguments.
2. `SourceCrawler` tests ignored descendants relative to the explicitly admitted
traversal root. It does not admit incidental `.workspace` trees as project code.
3. `FrontendSourceDocument` carries exact text, origin, presentation metadata,
read-only ownership and opaque frontend context. Definition locations optionally
carry that source; invalid path/range combinations are rejected. PBS preserves
source ownership separately from `SourceKind.PROJECT`; external ownership wins
when paths overlap. Existing default-empty frontend capabilities remain valid.
4. `ExternalSourceRegistry` belongs to `TcpLspServerHost`, not the shared compiler
bridge. It retains source/context together, with separate consumer grants,
acknowledged uses and reconnect validation. Repeated uses in one semantic
snapshot coalesce. Another reader's release cannot invalidate a retained source.
5. LSP negotiates external support and emits `prometeu-source:` destinations only
to supporting clients. External read, retain, release and revalidate requests
share server-issued consumer identity. The bridge uses retained content for
positions, hover, definition and highlighting. Unsupported consumers keep local
physical navigation without receiving unusable external targets.
6. VS Code registers a `TextDocumentContentProvider`, assigns PBS language, routes
hover/F12/highlighting and prevents external edit commands. Disconnect preserves
displayed text but disables queries until validation; the status bar explains
unavailable external documents. Changed revisions require fresh navigation.
7. MCP adds `readExternalSource` to `studio_language_query`. Task-owned consumers
survive short-lived sockets, acknowledge returned definitions, revalidate before
reuse, and release on task return/cancellation. Cross-task/project replay is
refused. Failed navigation releases unacknowledged results; failed responses
roll back newly retained sources. No human editor is needed.
### Example
A project definition on `Gfx.clear` opens the bundled SDK source. Hover/F12 on its
`LowGfx.clear` call reaches the host declaration. F12 on `Color` reaches the core
resource. The same operations work through MCP by reading the returned external
URI and querying positions in that text. A dependency under `.workspace/repos/lib`
uses the same presentation and write protection.
If that library changes on disk while a document is open, the retained document's
hover/F12 still use its old AST and old text. After disconnect, revalidation against
the changed source fails; clients must navigate again for new content and ranges.
## Validation evidence
Failures were reproduced before production changes: all four chain assertions
failed, both crawler/admitted-FileTable fixtures failed, and the old bridge test
confirmed SDK hover with empty bundled definition alongside working local F12.
Final module results (2026-10-07):
| Suite | Executed successfully | Skipped |
| --- | ---: | ---: |
| PBS frontend | 245 | 0 |
| Frontend API | 27 | 0 |
| Build pipeline | 141 | 15 existing disabled cases |
| LSP | 38 | 1 opt-in development-host case in the ordinary run |
| App: AutomationLspQueries, McpContract, CompilerProjectKnowledge | 24 | 0 |
| Core: TaskLanguageQueries | 1 | 0 |
| Actual VS Code Development Host, run separately | 1 | 0 |
All 477 executed JUnit cases passed across these scoped runs. TypeScript compilation,
`discussion validate` and `git diff --check` also passed. The disabled main-project
pipeline integration test was not treated as evidence.
The actual VS Code host exercised typing refusal, declaration selection, semantic
highlighting, hover, continued F12, a physical `.workspace` library with Unicode/CRLF,
reconnection and normal project edits. Provider tests exercised cached disconnected
text, matching/changed revisions, close and canceled reads. MCP tests used the actual
TCP server independently of VS Code, including task return, aliases, mixed rename
refusal and changed revisions. Registry tests covered multiple readers, distinct
projects, last release, task/session lifetime and canceled/unopened navigation.
The source-snapshot regression changed a dependency on disk after navigation and
verified that old hover/F12 still used the original declaration and semantic context.
Dedicated write-boundary checks refuse external didChange/didSave, formatting,
rename, prepareRename and code actions, including unnegotiated identities.
Commands are preserved in the plan-derived development instructions and test owners:
```sh
./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-compiler:prometeu-frontend-api:test :prometeu-compiler:prometeu-build-pipeline:test :prometeu-lsp:prometeu-lsp-v1:test --console=plain
./gradlew :prometeu-app:test --tests '*AutomationLspQueriesTest' --tests '*McpContractTest' --tests '*CompilerProjectKnowledgeTest' :prometeu-studio-core:test --tests '*TaskLanguageQueriesTest' --console=plain
npm --prefix tools/vscode-extension run compile
PROMETEU_VSCODE_DEV_TEST=1 ./gradlew :prometeu-lsp:prometeu-lsp-v1:test --tests '*ExternalSourceDevelopmentHostTest' --console=plain
```
Packaged Studio was excluded from the initial acceptance above. On 2026-10-07,
the user explicitly requested this additional validation. The existing
`InstalledKnowledgeTest` now launches its isolated probe with the Java runtime
from `installDist`, using distribution JARs plus test probe classes, with its working
directory and projects outside the checkout. It asserts that the frontend and LSP
bridge load from JARs and that SDK/core resources have `jar:` URLs.
The packaged gate passed:
```sh
./gradlew :prometeu-app:installedKnowledgeTest --console=plain
```
Besides reading the installed documentation and compiling its example, it verifies
project-to-SDK, SDK-to-host and SDK-to-core definitions, matching declaration lines,
exact SDK/core text against JAR bytes, read-only bundled descriptors, SDK hover and
semantic tokens, and source revalidation after reconnect. The project contains only
its original manifest and sources after navigation: no bundled source extraction.
The first run caught an incorrect cursor position in the test fixture; calculating
the position from the source fragment fixed the fixture. No production fix was needed.
This is a packaged resource/backend gate; it does not launch the Studio desktop or
repeat the VS Code UI checks against the installed process.
## Pitfalls
- Compiler success does not prove editorial resolution. Query the four surfaces.
- A physical path under the project root is not proof of editable ownership.
- Retaining text alone is insufficient: fresh analysis can attach different meaning
to old positions. Keep the corresponding semantic context.
- MCP socket closure is not task completion. Retain consumer state independently.
- VS Code normalizes escaped URI components. The first actual-host run exposed
mismatched identities from escaped slashes; emitted URIs now use unreserved
characters and keep names separately in metadata.
- `TextEditor.edit` is an extension programming API, not user typing. The real UI
gate uses the `type` command; backend edit proposals are checked independently.
If another extension changes a virtual buffer, the provider refuses queries whose
text differs from the retained revision.
- VS Code MarkdownString properties need direct inspection; JSON serialization can
show `{}` even when hover contains valid content.
- Enriching a shared definition DTO can accidentally expand references. Keep each
surface's admission policy explicit; the compatibility suite caught this coupling.
- Do not silently drop external edits from a mixed proposal. Refuse the operation.
## References
- [Compiler Spec 23](../../../docs/specs/compiler/23.%20Compiler%20Pipeline%20Entry%20Points%20Specification.md).
- [PBS Spec 5](../../../docs/specs/compiler-languages/pbs/5.%20Manifest,%20Stdlib,%20and%20SDK%20Resolution%20Specification.md).
- [PBS Spec 8](../../../docs/specs/compiler-languages/pbs/8.%20Stdlib%20Environment%20Packaging%20and%20Loading%20Specification.md).
- [Studio Spec 11](../../../docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md).
- [Extension guide](../../../tools/vscode-extension/README.md).
- [Historical physical-only policy, LSN-0068](../DSC-0039-pbs-lsp-go-to-definition/LSN-0068-pbs-go-to-definition-uses-editorial-lookup-and-physical-files.md).
- DEC-0031 / LSN-0049 still govern removal of the old embedded editor/VFS; none was restored.
@@ -0,0 +1,178 @@
---
id: LSN-0077
ticket: studio-persistent-mcp-connector
title: Integrated Studio MCP Through Stable Setup and Ephemeral Access
created: 2026-09-29
tags: [studio, mcp, connection, lifecycle, installation]
---
# Integrated Studio MCP: Stable Setup, Ephemeral Access
Owner: **studio**, MCP integration, project lifecycle and local installation.
DSC-0070 / DEC-0061 / PLN-0140 delivered this integration, including the user's
accepted revision for automatic preparation on project open. These identifiers
are historical references; maintained contracts are linked below. Automated
validation and the user's confirmation of final manual acceptance are recorded
separately.
## Original Problem
The original integration exposed a new HTTP port and bearer token on each Studio
restart. Developers had to configure their coding client repeatedly. Ad hoc
transport scripts then duplicated initialization, authentication and result
handling, obscuring native MCP tools and images.
The durable solution separates three lifetimes: installation, connection and
project authority. A stable client registration must not imply durable permission
to edit, and a transport interruption must not replay work.
## Consolidated Design
The distributed Studio artifact supports two modes. Normal invocation opens the
desktop. `StudioLauncher mcp --project <absolute-root>` runs a stdio connector
without JavaFX, Spring desktop composition, LSP or a second HTTP server. The coding
client owns that process; developers do not launch it manually for each project.
The desktop starts one shared loopback HTTP server. Opening a project prepares its
enabled integration automatically through the same neutral port used by scaffold
and the explicit DEV retry. An explicitly disabled integration remains disabled.
Preparation failure is visible in DEV and does not make the project unusable.
Opening a project does not publish credentials or grant control.
The macOS installation has a stable `current` reference pointing to a validated,
versioned distribution containing dependency JARs and Java. The native client
invokes the absolute installed Java path with a classpath/main/project argument
array. Updating the installation changes the reference, not every project's client
entry. Old versions remain available for rollback and existing processes.
The tradeoff is an additional lightweight JVM for stdio transport, plus managed
installation lifecycle. In return, there are no per-project launchers or copied
connector binaries, and execution does not depend on an interactive shell PATH.
## Configuration and Authority Have Different Owners
| Surface | Lifetime and responsibility |
| --- | --- |
| `.studio/setup.json` | Neutral integration intent; preserves runtime/editor settings |
| `.codex/config.toml` | Local installed command, arguments and canonical project binding; no transient credentials |
| `.studio/mcp/connection.json` | Protected, temporary discovery data published by human grant |
| Core grant/task/operation records | In-memory authority and receipts; never restored from configuration |
Preparation edits only a managed client entry, validates the result with a TOML
parser and preserves unrelated settings/comments. User-owned, edited or tracked
entries cause explicit conflicts. Initial client trust or reload may still be
required; Studio does not change approval policy.
Human grant publishes a fresh credential scoped to one canonical project root.
HTTP sessions are bound to that credential, and the server enforces scope even
for knowledge reads. Restricting only the connector would leave a direct HTTP
bypass. Acquisition still creates a separate task identity through shared Core
services.
## Publication Is Part of the Grant Transaction
Publication cannot be a best-effort snapshot listener. The neutral lifecycle port
coordinates preparation, publication, activation, invalidation and cleanup:
1. Save and verify documents under the existing handoff rules.
2. Acquire the OS publication lock and write a private temporary descriptor outside
the authority monitor.
3. Atomically publish, then activate under the grant generation fence. Acquisition
remains unavailable until the transition completes.
4. Abort failed or superseded grants and remove their provisional access.
5. Revoke credentials before asynchronous work cleanup; remove only the owned
publication and release its lock.
The lock file's inode is retained. Deleting it could let another process lock a
new inode while the first owner still holds the old one. The OS releases the lock
after a crash, allowing safe replacement of stale discovery data. Directories are
0700 and secret-bearing files 0600; Git exclusion alone is not access control.
Cleanup checks publication ownership so an old callback cannot delete newer data.
File cleanup failure must not prevent runtime cancellation.
## Reconnect Without Replaying Intent
The stdio connector initializes and lists its packaged catalog before Studio or a
grant is available. It verifies live instance, root and catalog identity before
forwarding. Calls preserve structured results and native image blocks; response
limits are separate from the smaller request limit.
Discovery and ping may be retried. Build and frame advancement must not be
resubmitted automatically after a lost response. Within the same authorized task,
recover by operationId/clientRequestId lookup. After restart, old in-memory
receipts are unavailable: report an unknown outcome and require a fresh grant/task
and an explicit next intent. Connection liveness and working/manual authority are
separate DEV states.
## Implementation Findings
- JSON-RPC numeric IDs must be compared by numeric value. Jackson can represent
the same wire number with different integer node types.
- Grant publication is asynchronous. Tests must await the transition without
blocking the JavaFX thread or assuming a button callback completes filesystem IO.
- `jlink` can generate read-only license files. Normalize staged runtime write
permissions so subsequent Gradle installation updates can replace them.
- An IntelliJ desktop can run from classes without a managed installation. A
generic “preparation incomplete” message hid this prerequisite. The specific
diagnostic now points to `:prometeu-app:stageStudioInstallation` and the optional
`studio.installationRoot` VM setting.
- Preparation belongs to project opening, not only creation or a manual DEV
button. Otherwise existing projects retain unnecessary onboarding friction.
- Capture data larger than 1 MiB must not inherit the request-body cap. The
connector bounds response size and body-read time separately.
## Verified Results and Acceptance
The full implementation gate recorded 839 passing tests, 15 existing skips and no
failures, including installation, desktop and real runtime gates. The later
missing-installation diagnostic and automatic-open revision passed their targeted
preparation, Core, app, architecture and runtime suites. Installation staging,
`git diff --check` and `discussion validate` also passed.
Process tests cover cold initialization, later grant and restart in one connector;
large images; root/session scope; stale identity/catalog rejection; lost build
response with execution count remaining one; unknown old-task receipts; concurrent
publisher JVMs and crash recovery; protected files; grant/close races; TOML
preservation; and stable installed Java across updates.
On 2026-09-29, after being asked specifically about the outstanding manual gates,
the user confirmed that all were finished. This closes the native Codex
acquire/build/image/release and reconnect-after-restart cycle, installation update
and graphical-client launch, and IntelliJ debugger attachment. The provenance of
this final evidence is **user-reported acceptance**, not an additional automated
run or an independently observed transcript. The implementation's automated
environment was macOS ARM64 with bundled Corretto 21.0.4 and Codex CLI 0.158.0
installed; that version inspection alone was not treated as native-client proof.
The prior HTTP-only acceptance from DSC-0068 was not substituted for these gates.
The first accepted integration remains Codex on macOS; other clients/platforms
and the embedded terminal are outside this delivery.
## Operational Example
Open the project in Studio. Its enabled client integration is prepared without a
separate per-project Run. Start the coding client in that project and satisfy its
initial trust/reload requirements. Grant access in DEV, acquire the task through
native tools, edit/validate, then release. After Studio restarts, grant again;
keep the client configuration unchanged. An old task is never restored.
For an IntelliJ desktop, run `p.studio.app.StudioLauncher` with the
`prometeu-app` classpath and Java 21. If a managed installation is missing, stage
it once with `./gradlew :prometeu-app:stageStudioInstallation`. An isolated
installation uses the `studio.installationRoot` desktop VM property. The MCP
stdio process remains client-owned; attach Remote JVM Debug to that process using
an explicit development-only loopback JDWP option. Do not configure the desktop
Run itself with `mcp --project` arguments.
## References
- DEC-0061 and PLN-0140: historical source decision and completed implementation
plan for DSC-0070; removed from active workflow during housekeeping.
- [Studio shell and project creation](../../../docs/specs/studio/1.%20Studio%20Shell%20and%20Workspace%20Layout%20Specification.md).
- [Project-local state and discovery](../../../docs/specs/studio/8.%20Project-Local%20Studio%20State%20Specification.md).
- [Core and adapter architecture](../../../docs/specs/studio/9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md).
- [DEV and authority](../../../docs/specs/studio/10.%20DEV%20and%20Automation%20Specification.md).
- [MCP contract and acceptance boundary](../../../docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md).
- [Setup and IntelliJ debugging](../../../README.md).
- [DSC-0068 baseline lesson](../DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md).
- DSC-0071: the separate embedded-terminal discussion; unchanged by this work.
@@ -0,0 +1,145 @@
---
id: LSN-0079
ticket: compiler-pbx-registry-conformance
title: Typed common IR through production PBX admission
created: 2026-10-14
tags: [runtime-integration]
---
## Original problem and ownership
Owner: compiler/general; interfaces: compiler/pbs and studio.
The old producer carried parameter/result slot counts without complete semantic
types and emitted a retired PBX function layout. A writer-only repair could not
recover signatures, distinguish nominal identities or describe closures and
trait implementations. The fix had to cross the entire common producer chain.
This lesson consolidates AGD-0076, accepted DEC-0063 and completed PLN-0142
(DSC-0074). Those workflow artifacts were removed by housekeeping after their
normative content and evidence were propagated. The active integration umbrella
is [AGD75](../../workflow/agendas/AGD-0075-studio-runtime-readiness.md).
## Consolidated decisions
Use stable declaration references before assigning deterministic dense image
IDs. Preserve Struct/Trait nominal identity; canonicalize Builtin imports,
Array elements and Fn signatures. Names are descriptive, not nominal keys.
Parameters, results, captures, implementations and lifecycle roles are explicit
common values, preserved through IRVM, optimization and emission.
The common IR remains serializable by design, but a concrete codec was
explicitly deferred. Complete representation does not require selecting a
transport format. References avoid recursive Java object graphs and the public
contract audit rejects mutable or frontend-specific shapes.
PBS is one frontend. Optional and Result already belong to PBS's normative
language contract and have parser/semantic implementations. Defects in their
executable lowering do not justify new backend categories or rejection rules.
Their implementation and carrier choices remain frontend-owned. The user
explicitly scoped consumer migration to subsequent tickets and a single AGD75
integrated delivery. No PBS semantics were added to this backend change.
## Final implementation
- IRRegistry and FunctionMetadata represent all five type categories, ordered
signatures/captures, roles and implementations. Aggregation remaps callable
references while preserving stable type identity.
- LinkedRegistry canonicalizes imports/structural declarations deterministically
with an iterative dependency traversal. Nominal anchors permit recursion;
purely structural cycles reject.
- Lowering derives widths from semantic signatures, links typed operands and
remaps implementation targets. IRVM coherence and optimization preserve the
Registry and function metadata.
- The PBX writer emits the 32-byte header and all eight mandatory sections,
optional debug, strict UTF-8, exact function records and explicit empty capture
environments. Width caches are not serialized. Constant deduplication now
relocates PUSH_CONST indices rather than silently changing their meanings.
- Local verification decodes all function ranges, validates references and
operand categories, forbids retired/raw opcodes and analyzes reachable stack
and type facts to convergence. Conflicts become Unknown; exact semantic groups
retain provenance when available. Unknown remains subject to runtime checks.
- Production loading remains authoritative for native identity/capability/ABI,
runtime budgets and executable admission.
- Studio previously discarded error.details when a headless response rejected
boot. AutomationFailure now preserves the entire runtime error envelope,
including initialization, binding and resource details, through MCP output.
## Examples and pitfalls
A `vec2 -> vec2` function has logical arity one/one and derived slot widths two/two.
The function record writes the two TypeId lists, not the numbers two/two. A test
compares that record with independent fixed bytes from the runtime contract.
A capturing body is not a direct-call target. MAKE_CLOSURE names the body and
expected Fn type, consumes its explicit capture groups and produces a callable.
CALL_CLOSURE consumes that callable after the explicit arguments. The synthetic
frontend test proves this path without PBS source, SDK or language ASTs.
Jumps contain absolute offsets from the current function start. They are not
relative to the next PC. A taken jump to function end is a return boundary;
ordinary fallthrough is invalid. These details were checked against the actual
runtime verifier, not inferred from older emitter behavior.
Do not derive type identity from slot width, spelling or display names. Do not
claim a self-round-trip proves external conformance. Do not treat parser tests
as execution evidence or a load-only argument-taking entry as a boot test.
Initialization diagnostics have null outer executed PC. A verifier PC remains
nested in initError.load.pc; file offsets remain offsets. Preserve the original
JSON structure rather than flattening it into human-readable messages.
## Qualification evidence
Runtime: `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`.
Platform: macOS 27.0.1 arm64. Rust harness uses the runtime Cargo.lock, default
load limits and NONE capabilities except the positive native case (SYSTEM).
Resource-negative cases explicitly lower Types, TemporaryBytes or Work.
Runtime checkout remained unchanged.
| Gate | Result |
| --- | --- |
| Build-pipeline suite | 178 tests: 163 passed, 15 skipped, no failures |
| Frontend-api suite | 28 passed |
| PBS suite | 245 passed; not a claim of complete executable migration |
| Headless process suite | 9 passed, including six observed runtime fault payloads |
| Architecture suite | 17 passed |
| Independent binary oracle | Exact 194-byte minimal image and fixed vec2 function bytes |
| Production loader positives | 12 admitted images, including native binding |
| Genuine execution | 11 programs: direct/common path, closures/captures, trait, Array/Dynamic, joins, roles, intrinsic and native; vec2 signature is load-only |
| Production negative corpus | 32 rejected malformed/binding/code/resource fixtures |
| Workflow and patch integrity | discussion validate and git diff --check passed |
The 15 skipped tests are older conditional integration adapters. The dedicated
production harness above ran explicitly; their skip state is not substituted
for runtime evidence. The intrinsic/native catalogue goldens are serialization
fixtures and do not claim current PBS catalogue compatibility.
Reproduce with the commands in
[the harness README](../../../tools/pbx-conformance/README.md). The harness
creates its Cargo build outside the runtime checkout and saves generated PBX and
observed JSON under the build-pipeline build directory.
## Remaining integration work
The runtime LoadReason enum has four values missing from the published headless
schema: LifecycleRole, LifecycleSignature, DuplicateLifecycleRole and
NonFiniteValue. The corpus observes the first and last. Both payloads fail the
original schema solely because of the missing enum value. The harness explicitly
reports this upstream gap, validates the original payload with that single enum
addition, and leaves the payload unchanged. It does not claim those two cases
conform to the unmodified schema. Runtime must correct the schema under AGD75.
PBS typed producer migration, Optional/Result executable lowering, catalogue
alignment, installed runtime delivery, hook selection, memcard gating and
persistence remain with their consumer tickets. The common schema and synthetic
producer work without those features. There is no legacy PBX fallback and no
slot-to-type inference to conceal an incomplete handoff.
## References
- [Typed common Registry/PBX specification](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md)
- [Backend conformance matrix](../../../docs/specs/compiler/22.%20Backend%20Spec-to-Test%20Conformance%20Matrix.md)
- [Runtime qualification harness](../../../tools/pbx-conformance/README.md)
- Runtime sources: registry_v0.rs, program_image.rs, registry_verifier, and
devtools/headless-protocol/response.schema.json at the revision above.
@@ -0,0 +1,182 @@
---
id: LSN-0080
ticket: compiler-runtime-catalog-parity
title: Manual runtime catalog port and independent conformance
created: 2026-10-15
tags: [runtime-integration]
---
## Original problem and ownership
Owner: `compiler/general`; consumers: `compiler/pbs`, `vm-arch` and `studio`.
This lesson consolidates AGD-0077, accepted DEC-0064 and completed PLN-0143
(DSC-0075), including the user's explicit acceptance revision on 2026-10-15.
Their workflow files were removed after propagation and CLI housekeeping.
The runtime published 105 intrinsics with 18 fields and 15 builtin constants
occupying 16 slots. Studio had 42 intrinsic records with 12 fields, no constant
mirror and a disabled parity test. Copying the CSV could not update the compiler's
manual ABI representation, reject retired endpoints or preserve new effects.
Against the previous Studio catalog, the port added 82 identities, removed 19
and updated 23 retained identities.
## Consolidated decision
The runtime owns identities, layouts, constant values, effects and costs.
Studio imports both CSVs unchanged at an explicit target revision, inventories
the differences, then manually ports the compiler representation and consumers.
`IRVMIntrinsicDefinition` represents the runtime supported by this compiler
version. Normal compilation uses local versioned code/resources; it neither
queries the latest runtime nor depends on a sibling checkout.
Manual maintenance keeps compiler adaptations explicit and reviewable, at the
cost of maintaining a port. Active comparisons against independently exported
CSV data detect drift. Enum generation, a shared implementation library and
moving the backend were not required. An explicit provider check uses runtime
source/tests to establish behavior and export provenance. A different runtime
commit is not itself proof of incompatibility; revision and hashes identify
the evidence target without introducing version negotiation.
Read dispatch, verifier and execution tests as well as CSVs. CSV fields describe
the published shape but cannot explain all null handling, native-reference
validation, traps or charging behavior.
## Final implementation
- `IRVMIntrinsicDefinition` and `IRVMIntrinsicRegistry` cover all 105 entries and
18 published fields. Exact name/version resolution and ID lookup reject
retired identities; old IDs are not compatibility aliases.
- `IRVMBuiltinConstantDefinition` independently groups all 15 constants by
target/name/version, preserving ordered slots and exact values/bits. Its
materialization supplies common bytecode constant values.
- Lowering checks caller counts against the selected definition. IRVM validation,
emission and bytecode precheck reject unknown IDs and inconsistent signature
caches, including unknown IDs in unreachable code. Module-only IRVM emission
derives intrinsic signatures from the same target definitions.
- Explicit carrier mappings distinguish Int32, Int64, Float, Bool, String,
color and Random. Unsupported tokens fail. Static facts do not claim to prove
native handle identity or session validity; the runtime remains authoritative.
- Compiler and PBS SDK JARs package both CSVs and provenance from checked-in
mirrors at `runtime-catalog/compiler/` and `runtime-catalog/pbs-sdk/`.
Installed-resource tests validate actual JAR bytes/hashes outside the checkout.
- Active parity tests, synthetic common-IR behavior and the production runtime
harness provide separate evidence. No new PBS facade or numeric/random
algorithm was implemented in this common backend work.
## Examples and pitfalls
**A retained name can have a different ABI.** `input.touch.x/y` moved to
`0x2134/0x2135`, lost their receivers and return Int64. Resolving the name alone
is insufficient; stale caller counts must fail. Input metadata coverage does
not mean the existing PBS input syntax already lowers to these direct queries.
**Constants are not generic zero-argument intrinsics.** `mathf.pi` and
`mathf.tau` materialize Float bits `0x400921FB54442D18` and
`0x401921FB54442D18`. `vec2.zero` materializes two Float slots and has no
intrinsic ID. Some color names independently have both mechanisms, which does
not establish a rule for other constants. Pool deduplication may share the
zero value but must preserve both emitted vec2 components.
**Determinism is not purity.** All four Random intrinsics mutate guest state;
only `random.new` allocates. The tested common program aliases one generator,
discards a `next` result, then mixes `nextf`, `range` and `next`. Removing the
discarded call changes the sequence. Optimized and unoptimized executions
matched the independent seed-42 vector and each used 100 cycles/20 steps.
`random.range` preserves base cost 4, cost 8 per attempt and limit 64. The VM
performs charging; storing metadata does not create a second Java scheduler.
**Static and dispatch rules can differ.** Runtime `abi_mask` permits String
only for intrinsic String arguments, while `value_matches_abi_type` accepts
String or null in dispatch. The Studio precheck therefore rejects a proven
null at load time. The production loader confirmed that rejection with
`LOAD_INVALID_CODE/TypeMismatch`; a String `#AABBCCDD` executed to color
`0xAABBCCDD`. Random's static reference mask includes null, leaving native
handle validity to runtime checks.
Do not use a serializer of the Java enum as its own expected catalog, infer
carrier identity from slot width, disable stale fixtures to hide regressions,
or equate JAR resource parity with successful PBS or installed-host execution.
## Qualification evidence
Selected runtime: `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, clean checkout.
Host: macOS 27.0.1 arm64; JDK 25 for Studio build and JDK 21 for the installed
launcher. Provider exporter used Cargo test profile/default features; the
production VM harness used dev profile/default features and default load
limits. New catalog fixtures used NONE capabilities. Runtime was not modified.
| Artifact | SHA-256 |
| --- | --- |
| INTRINSICS.csv | `0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa` |
| BUILTIN_CONSTANTS.csv | `e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039` |
| Check | Result |
| --- | --- |
| Build-pipeline suite | 187 tests: 175 passed, 12 existing skips, zero failures |
| PBS suite | 245 passed, zero failures; no claim of executable PBS migration |
| Normal catalog parity | All fields, identities, constant bits/groups and packaged hashes passed |
| Explicit provider check | Committed-source/mirror/hash comparison and real runtime exporter test passed; missing provider failed as required |
| Catalog execution corpus | Random with alias/discarded mutation, exact constants, vec2.zero and String conversion passed on the actual VM |
| Admission/availability negatives | Removed unreachable ID and proven-null String rejected; known input loaded then trapped UNAVAILABLE without hardware |
| Installed catalog gate | Passed using actual compiler/SDK JAR resources and bundled launcher outside the checkout |
| Full installed example gate | Failed before and after the port: missing typed metadata for Gfx.clear; explicit consumer handoff and acceptance revision below |
| Workflow/patch integrity | `discussion validate` and `git diff --check` passed |
The complete existing PBX harness corpus also passed with its already documented
runtime schema exceptions: LifecycleRole and NonFiniteValue remain absent from
the published fault-schema enum. The harness reports these gaps and preserves
payloads; this port does not claim the upstream schema was corrected.
Reproduce the catalog and consumer checks from the repository root:
```sh
./gradlew :prometeu-compiler:prometeu-build-pipeline:test :prometeu-compiler:frontends:prometeu-frontend-pbs:test --console=plain
./gradlew :prometeu-app:installedKnowledgeTest --tests '*installedCompilerAndSdkCarryTheSameVerifiedCatalog' --console=plain
python3 tools/runtime-catalog/verify.py --runtime ../runtime
python3 tools/pbx-conformance/run.py --runtime ../runtime
```
## Accepted boundary and remaining consumer work
The full `:prometeu-app:installedKnowledgeTest` failed with
`LOWER_IRVM_INVALID_TYPED_REGISTRY: typed function metadata required: Gfx.clear`.
The same failure was reproduced on an independent archive of previous Studio
HEAD `bd5694dbdf5b214b4295fc8e01ddbe0ba5479599`; only diagnostic stdout was
enabled in its test probe to reveal the exact existing error.
On 2026-10-15 the user explicitly approved concluding catalog acceptance and
leaving that correction with AGD-0078. DEC-0064 and PLN-0143 recorded this precise
revision before housekeeping: the installed catalog probe is this delivery's
mandatory installed gate; the full example test remains active and failing.
All catalog, common behavior, affected module and provider-execution checks
remain required and passed. No general waiver for future failures was granted.
- AGD-0078 owns PBS typed metadata, existing input/types and vec2 source
materialization. Correct the Gfx.clear producer path and rerun the full
installed example gate; do not weaken the common typed Registry contract.
- AGD-0083 owns math/mathf facades, overloads and source constant exposure.
`PbsExecutableBodyLowerer.emitBuiltinConstFetch` still assumes an intrinsic
with one return; pi/tau require the independent constant materialization path.
- AGD-0084 owns PBS Random handles, storage, aliasing and source replay tests.
Common-IR execution provides a base, not proof of the future PBS facade.
- AGD-0080 owns actual installed-runtime Build/Play/headless qualification.
Catalog resources identify the compiler target without proving that flow.
These handoffs and the explicit acceptance revision are recorded in the active
agendas and [integration umbrella](../../workflow/agendas/AGD-0075-studio-runtime-readiness.md).
Future catalog updates must review source, imports, manual consumers, provenance
and behavior together. Roll back that set together if necessary.
## References
- [Normative catalog support](../../../docs/compiler/general/specs/runtime-catalog-support.md)
- [Typed common Registry/PBX contract](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md)
- [VM mirror and provider verification policy](../../../docs/vm-arch/README.md)
- [Production runtime harness](../../../tools/pbx-conformance/README.md)
- Runtime sources at the recorded revision: catalog.rs, builtins.rs,
input_intrinsics.rs, math_intrinsics.rs, random_intrinsics.rs, random.rs,
registry_verifier/{heights,types}.rs and tests/numeric_contract.rs.
Workflow tooling note: the installed CLI registers an existing lesson but has
no lesson-allocation command. LSN-0080 was selected by reading the next counter;
`discussion housekeep` performed all index mutations and counter advancement.
@@ -0,0 +1,83 @@
---
id: LSN-0081
ticket: pbs-existing-types-input-alignment
title: PBS Typed Values and Direct Input Queries
created: 2026-10-15
tags: [compiler/pbs, runtime-integration]
---
## Context and result
Owner: **compiler/pbs**, with shared compiler IR and installed Studio consumer propagation. DSC-0076 (AGD-0078, accepted DEC-0065, completed PLN-0144) aligned existing PBS values and input with the published runtime. The original object chain exposed intermediate input objects that had no useful runtime representation. PBS also omitted exact executable function metadata, causing the full installed example to fail at `Gfx.clear` under the shared typed registry validator.
The delivered implementation replaces those chains, produces typed function metadata, preserves complete value groups, and passes both actual-runtime execution and the full installed knowledge gate. The completed agenda, decision and plan were removed through framework housekeeping; this lesson preserves their implementation evidence.
## Public selectors and direct runtime endpoints
Use a nominal selector value and a public query:
```pbs
let button = Button.A;
let pressed = Pad.pressed(button);
let frames: long = Pad.hold(button);
let x: long = Touch.x();
```
`Button` has twelve cases: Up, Down, Left, Right, A, B, X, Y, L, R, Start, Select. The four Pad operations are pressed, released, down and hold. Each public function dispatches through an exhaustive enum switch to one of the 48 zero-argument LowPad endpoints. For example, `Pad.pressed(Button.A)` reaches `LowPad.a_pressed()`, bound to `input.pad.a.pressed`. The selector is evaluated once and only the selected endpoint reads input. Obtaining or passing a Button has no input effect. Constant specialization is unnecessary for correctness.
Touch exposes pressed/released/down as Bool and hold/x/y as Int64. The implementation uses existing runtime endpoints, with no ABI or lifecycle redesign. `Input.pad().a()` and aliases of its intermediate object are removed; import diagnostics explain the replacement. Strings, integers and unrelated enums cannot substitute for Button. The source type remains nominal even though its executable carrier is Int32.
## Exact values must survive frontend lowering
The explicitly accepted integer mapping is `int` to Int32 and `long` to Int64. Integer literals default to int; an explicit long context admits Int64 literals. Conversions use existing `as` syntax. Variables of different numeric widths require explicit conversion. Pad.hold and Touch.hold/x/y therefore return long.
`PbsRuntimeTypes` connects source types and declarations to canonical registry types and exact parameter/result groups. Callable lookup includes arity so overloaded SDK functions do not overwrite each other's signatures. Existing unsupported source types retain their previous executable boundary; shared strict metadata validation was not relaxed to admit them.
Locals, parameters, calls and returns carry whole groups: vec2 uses two Float slots and pixel uses two Int64 coordinates plus color. Slot count alone never establishes type identity. Builtin constants are resolved through the shared constant catalog: vec2.zero materializes two Float zero values, without inventing a one-result intrinsic. The backend validates the declared group width against the catalog materialization.
Named application first evaluates expressions in source order, stores their complete groups, and then loads those values in parameter order. The runtime proof calls `combine apply (y: Probe.y(), x: Probe.x())`: effects record Y then X while combine receives x then y. Its final oracle is 211020.
## Qualification evidence
Qualification date: 2026-10-15; platform: Darwin arm64. Studio base revision: `603ed012272b137361ba618f6887f015f7317803` plus this delivery's working-tree changes. Runtime revision: `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`. The runtime checkout was not modified. Default Gradle configuration; controlled input and no-platform configurations in the real runtime harness.
```sh
./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-compiler:prometeu-build-pipeline:test :prometeu-compiler:prometeu-frontend-api:test :prometeu-lsp:prometeu-lsp-v1:test :prometeu-app:installedKnowledgeTest --console=plain
CARGO_TARGET_DIR=/tmp/pln144-cargo-target python3 tools/pbx-conformance/run.py --runtime ../runtime
git diff --check
discussion validate
```
| Suite | Passed | Existing skips | Failures/errors |
| --- | ---: | ---: | ---: |
| PBS frontend | 246 | 0 | 0 |
| Build pipeline | 179 | 12 | 0 |
| Frontend API | 28 | 0 | 0 |
| LSP | 38 | 1 | 0 |
| Full installed knowledge | 2 | 0 | 0 |
`PbsRuntimeAlignmentTest` generates 114 PBX programs through the production compiler, lowerer, emitter and preload verifier. The actual runtime harness loads and executes all of them:
- 48 Pad combinations using a local Button passed through a typed function, plus 48 direct constant combinations; controlled input asserts the exact returned value and exactly one selected read.
- All six Touch queries, including signed x/y values. All 102 input programs are also executed without a platform and must trap with TRAP_UNAVAILABLE.
- Twelve value/fault programs cover Int32, Int64, Float, String, color, vec2, pixel, tuple returns, named evaluation order, Int32 wrapping, checked narrowing and division by zero. Bool is covered by input queries. Registry default layouts are checked for all eight existing canonical value types.
Frontend negatives cover invalid Button arguments, mixed int/long variables, literal overflow and migration diagnostics. Existing shared tests continue to cover wrong typed signatures, stale touch signatures, unreachable removed IDs, and lifecycle assembly. The original full installed failure at `Gfx.clear` is fixed. This does not claim completion of the separate Studio desktop integration agenda. Existing upstream fault-schema gaps (LifecycleRole/NonFiniteValue) remain explicitly reported by the shared harness, without suppressing this delivery's oracles.
## Pitfalls and reusable patterns
- A dotted builtin target is already a complete catalog name: use `input.pad.a.pressed`, not a partial `a.pressed` that silently loses its owner.
- A numeric literal's context must reach calls, returns and constructors; parsing an integer into a wide host value is insufficient to give it an Int64 guest type.
- Handle the signed minimum literal before rejecting its positive magnitude. A positive value above Int64 maximum must produce a diagnostic, not become zero.
- Preserve catalog overflow behavior: Int32 addition wraps; out-of-range narrowing traps with TRAP_NUMERIC_RANGE. Do not assume all numeric operations trap on overflow.
- A switch can omit its final comparison only when exhaustive coverage is proven. Non-exhaustive statement switches must not execute an unmatched final arm.
- A catalog or structural test alone cannot prove a frontend consumer. Generate PBS programs, run the real VM, and keep the full installed example as an independent gate.
- Publish the focused canonical spec in installed knowledge as well as in the checkout. SDK exports, diagnostics, language services and examples must migrate together.
## References
- [Normative PBS input and existing-value contract](../../../docs/compiler/pbs/specs/input-and-existing-type-runtime-alignment.md)
- [Shared runtime catalog contract](../../../docs/compiler/general/specs/runtime-catalog-support.md)
- [Typed registry and PBX contract](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md)
- [PBS source-to-PBX qualification](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java)
- [Actual-runtime harness instructions](../../../tools/pbx-conformance/README.md)
@@ -0,0 +1,106 @@
# Runtime catalog support
Status: normative. Owner: `compiler/general`.
## Authority and update boundary
The runtime owns intrinsic identities, ABI layouts, effects, costs and builtin
constants. Studio MUST keep byte-identical copies of the selected provider's
`INTRINSICS.csv` and `BUILTIN_CONSTANTS.csv` under `docs/vm-arch`. The sibling
`runtime-catalog.properties` records the provider revision and SHA-256 of both
files. These mirrors are reference data, not an independent runtime contract.
An update MUST import both catalogs, inventory additions/removals and field
changes, manually port the compiler consumers, verify behavior and update the
packaged provenance together. A CSV-only change is not a completed integration.
Read the selected runtime's implementation and tests when porting behavior;
CSV fields alone do not explain dispatch, reference validation or charging.
Normal builds MUST use local versioned sources and resources. They MUST NOT
query the latest runtime or depend on a sibling runtime checkout. An explicit
provider verification command requires the recorded revision and fails when
the source is missing, modified or different. That evidence requirement does
not make a different runtime revision inherently incompatible.
## Manual intrinsic representation
`IRVMIntrinsicDefinition` is the explicit compiler representation of its runtime
target. It MUST preserve every published record and field: IDs, canonical
identity/version, owner/name, argument/result counts and layouts, determinism,
allocation, parameter names, guest-state mutation, base/fixed cycles, cost model,
attempt cycles and maximum attempts. `IRVMIntrinsicRegistry` resolves exact
identities and IDs. Retired entries MUST NOT survive as aliases.
Lowering MUST validate caller-supplied counts against the selected definition.
Validation and emission MUST reject unknown IDs and inconsistent signatures,
including unknown IDs in unreachable bytecode. A name retained by the provider
does not imply an unchanged ABI; input touch coordinates illustrate a change
from receiver-based calls to zero-argument queries.
Carrier mappings MUST be explicit. Int32 and Int64 remain distinct despite equal
slot widths. Layout order and complete groups MUST be preserved. Native color
and Random contracts MUST NOT be inferred from arbitrary one-slot integers or
references. Producer checks validate proven carrier facts; runtime admission
and execution remain authoritative for reference identity, session ownership,
platform availability and traps. Unsupported carrier tokens MUST fail explicitly.
Static intrinsic String facts MUST follow the provider verifier's String-only
mask: a proven null is rejected at load time. The dispatcher's acceptance of
null for the String ABI does not broaden that static rule. Random's static
reference mask includes null; native handle validity is still checked at runtime.
Determinism MUST NOT be interpreted as purity. In particular, all Random calls
mutate guest state. Reachable calls cannot be removed, merged or reordered in a
way that changes effects, traps or charged work, even when their results are
discarded. Variable-cost descriptors MUST remain variable: `random.range` has
base cost 4, cost 8 per attempt and a maximum of 64 attempts in the selected
contract. The runtime performs charging; Java metadata does not implement a
second scheduler or random algorithm.
## Constants
Builtin constants have their own lookup identity `(target, name, version)` and
ordered slot values. They MUST NOT be resolved by inventing an intrinsic with
the same name. Some color names have both a constant and a separately published
intrinsic; this does not establish a generic equivalence.
The manual constant representation MUST preserve all carriers and exact values.
Float constants are materialized from published IEEE-754 bits. `vec2.zero` is
two ordered Float slots and has no intrinsic ID. Materialization and emission
MUST preserve the whole group; source-language exposure remains frontend-owned.
## Distribution and conformance
The compiler JAR packages the two catalogs and provenance at
`runtime-catalog/compiler/`; the PBS SDK JAR packages the same three files at
`runtime-catalog/pbs-sdk/`. Both copies MUST derive from the checked-in mirrors
and agree byte-for-byte. The metadata identifies the represented target contract;
it does not assert that every catalog entry already has a PBS facade.
Normal tests MUST compare every manually maintained field with the independently
published CSV, verify constant bits/groups and check packaged hashes. They MUST
run without a runtime checkout and MUST NOT be disabled or silently skip parity.
Explicit provider checks also run the real runtime catalog exporter test;
parsing only one Rust table is insufficient because the catalog spans several
implementation modules.
Behavioral tests MUST cover changed signatures, retired IDs, scalar carriers,
complete groups, stateful call order and emitted values. Evidence from the
selected runtime MUST identify revision, platform and configuration and distinguish
catalog comparison, image loading and execution. PBS facade delivery and
installed-runtime qualification remain separate consumer claims.
See [typed common Registry and PBX v0](typed-registry-and-pbx-v0.md) for the
frontend/backend boundary and [mirror policy](../../../vm-arch/README.md) for
explicit verification commands.
## PBS consumer
The [PBS input and value alignment contract](../../pbs/specs/input-and-existing-type-runtime-alignment.md)
requires typed Pad/Button dispatch, direct LowPad endpoints and complete builtin
value groups. Frontend numeric literal and builtin-constant operations retain
explicit identity and width; common lowering resolves constant groups against
`IRVMBuiltinConstantDefinition` and checks the declared result width. PBS does
not introduce another catalog. Source execution and the full installed example
are separate consumer gates beyond CSV parity.
@@ -0,0 +1,182 @@
# Typed common Registry and PBX v0
Status: normative. Owner: `compiler/general`. Runtime contract reference:
`runtime` revision `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`,
`docs/specs/runtime/02c-program-registry-and-pbx-v0.md` and
`docs/vm-arch/ISA_CORE.md` in that repository.
## Ownership and handoff
Every executable frontend MUST provide its semantic types through the common
`IRRegistry` model and typed `FunctionMetadata`. The backend MUST NOT inspect
language ASTs, PBS names, Optional/Result syntax, or frontend-specific classes.
Language carriers and their lowering remain owned by the frontend. A carrier
can use ordinary Struct, Array, Trait, Fn and Builtin declarations without
introducing a language category in the backend.
The public model consists of immutable values and ordered `ReadOnlyList`
collections. References use explicit declaration keys and callable IDs, not
object identity or recursive object graphs. It is serializable by design;
no concrete IR codec, wire format or persistence protocol is selected.
A function declares ordered named parameters, ordered logical results, ordered
captures, a lifecycle role and an optional name. Empty names differ from absent
names. Captures are an environment, never hidden parameters. Slot counts are
derived from types; existing count fields are checked caches, not semantic
input. Missing nonempty type metadata is an invalid handoff, not a request to
infer types from counts. Optimizers MUST preserve metadata and typed operands.
## Identity and linking
TypeId, FunctionId and ImplementationId are separate dense image-local index
domains. Index zero is valid. Trait references use TypeIds; field and method
indices are local to their owner. Source declaration keys MUST identify the
same declaration across repeated module imports and distinguish unrelated
nominal declarations, even when names and shapes coincide.
Linking is deterministic. The selected physical entry is FunctionId zero;
remaining functions follow canonical module/callable/source ordering. Struct
and Trait retain nominal identity. Builtin imports deduplicate by BuiltinId,
Array by canonical element identity, and Fn by ordered parameter/result type
identities, excluding names. Forward references and recursion through nominal
anchors are valid. Pure Array/Fn cycles are invalid. Every reference must
resolve before emission. Frontends should supply only used imports.
| BuiltinId | Type | Slots |
| --- | --- | --- |
| `0x0001` | color | 1 |
| `0x0002` | vec2 | 2 |
| `0x0003` | pixel | 3 |
| `0x0010` | Int32 | 1 |
| `0x0011` | Int64 | 1 |
| `0x0012` | Float | 1 |
| `0x0013` | Bool | 1 |
| `0x0014` | String | 1 |
| `0x0015` | Dynamic | 2 |
| `0x0016` | Random | 1 |
The retired input IDs `0x0100`–`0x0102` have no aliases. Struct, Array and Fn
values occupy one reference slot; Trait values occupy two slots. Width does
not establish type identity or authorize conversion.
## Binary contract
All fields are little-endian. The header is 32 bytes: `PBX\0`, u16 version zero,
zero endian/reserved bytes, u32 section count and twenty zero reserved bytes.
Directory entries are u32 kind, file-relative offset and length. Ranges must
not overlap or overflow. The version remains zero; no legacy fallback exists.
Mandatory sections are constants (0), functions (1), Code (2), exports (4),
syscalls (5), types (6), implementations (7) and captures (8). Debug (3) is
optional. Empty tables contain a u32 zero count. Code is raw bytes, not a
counted table. An empty table set is serializable but is not an executable
program: production loading requires a valid ordinary entry.
Lists have u32 counts. Optional names use u8 presence 0/1, then u32 UTF-8 byte
length and bytes when present. UTF-8 is strict. Named types contain TypeId then
optional name; results and captures contain TypeIds without names.
| Record | Ordered payload |
| --- | --- |
| Type | u8 tag, optional name, category payload |
| Builtin (tag 0) | u32 BuiltinId |
| Struct (tag 1) | named fields |
| Array (tag 2) | u32 element TypeId |
| Trait (tag 3) | methods: optional name, parameters, results |
| Fn (tag 4) | parameters, results |
| Function | u8 role, optional name, parameters, results, u32 Code offset, length, extra locals, max temporaries |
| Implementation | u32 owner TypeId, trait TypeId, method count, ordered FunctionIds |
| Captures | function count and one ordered TypeId list per function, including empty lists |
Function Code offsets are Code-relative. Parameter/result slot counts MUST NOT
be serialized. Max temporaries zero means zero. Signature names are independent
of debug names. Constants retain tags Null 0, Int64 1, Float64 2, Boolean 3,
String 4 and Int32 5. Float payloads must be finite. Constant deduplication
requires relocating every PUSH_CONST index; changing only the table is invalid.
Roles are None 0, BeforePause 1, BeforeResume 2 and MemcardBoot 3. Nonzero roles
are unique, cannot target entry zero and cannot capture. Pause/resume have empty
signatures; MemcardBoot has `(Int64) -> Int32`. This metadata does not implement
frontend hook selection, mem.bootstrap gating or persistence.
Implementations are unique per Struct/Trait pair, complete and ordered. Each
method target has an exact signature with a concrete Struct receiver first,
followed by the trait method's explicit parameters. Targets cannot capture.
## Instructions and verification
Instructions use u16 opcodes. Jump operands are absolute u32 byte offsets from
the current function start, not displacements from the next instruction.
A taken jump to the current function end is a return boundary; ordinary
fallthrough past the end is invalid.
| Opcode | Typed operands |
| --- | --- |
| MAKE_CLOSURE `0x52` | FunctionId, Fn TypeId |
| CALL_CLOSURE `0x53` | expected Fn TypeId |
| GET_CAPTURE `0x57` | capture group index |
| CALL_TRAIT `0x58` | Trait TypeId, method index |
| DYN_PACK/UNPACK/CAN_UNPACK `0x90`–`0x92` | TypeId |
| Reference operations `0x93`–`0x96` | source TypeId, target TypeId |
| STRUCT_NEW `0xa0` | Struct TypeId |
| STRUCT_GET/SET `0xa1`–`0xa2` | Struct TypeId, field index |
| Array operations `0xa3`–`0xa6` | Array TypeId |
Direct CALL cannot target a capturing body. Closure signatures match exactly.
Retired SPAWN/YIELD/SLEEP (`0x54`–`0x56`) and raw producer SYSCALL are invalid,
even when unreachable. All function ranges must decode completely; references,
categories, operand boundaries, finite immediates and branch destinations are
checked even in unreachable instructions.
Reachable analysis uses a bounded worklist. Parameters initialize local facts;
extra locals start Null and may change type. Joins require equal temporary
heights. Equal facts survive; conflicting facts widen to Unknown. Type errors
are diagnosed after convergence. Unknown alone neither proves compatibility
nor justifies rejection. Runtime group checks remain authoritative. RET and
jump-to-end require exact result width and compatible known facts. GET/SET_LOCAL
address only parameters plus extra locals. No implicit numeric, trait or Dynamic
conversion is introduced by linking, writing or verification.
HOSTCALL references a declared canonical `(module, name, version)` identity
with exact argument/result slot ABI. Duplicate identities with conflicting ABI,
unused declarations and invalid indices are rejected. Only the runtime loader
binds capabilities and rewrites HOSTCALL to SYSCALL. Intrinsic signatures are
explicit compiler metadata; their IDs and definitive ABI remain runtime-owned.
## Bounds and diagnostics
Product ceilings: PBX 64 MiB, Code 32 MiB, 65,536 types and functions each,
262,144 implementations, 1,048,576 nested records, names 4,096 bytes individually
and 4 MiB aggregate, frame 16,384 slots and results 1,024 slots. Runtime admission
also owns retained Registry 64 MiB, scratch 128 MiB and work 268,435,456. A guest
cannot raise these limits. Java validation is not a substitute for runtime
allocation accounting or final `ValidatedProgramImage::load` admission.
Compilation failures use common LOWER_IRVM/MARSHAL stage diagnostics. Load,
binding and resource failures remain distinct from executed traps. Studio
preserves the full runtime error envelope in `AutomationFailure.runtimeError`,
including null fields and native binding details. The outer initialization
fault PC remains null. A verifier PC stays in `initError.load.pc`; a file offset
MUST NOT become an executed PC.
## Reproducible conformance
Run the focused common tests, then the production harness:
```sh
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest'
python3 tools/pbx-conformance/run.py --runtime ../runtime
```
The Java tests write `build/registry-conformance` inside the build-pipeline
module. The harness builds outside the runtime checkout using its Cargo.lock,
loads Java-produced bytes, executes admitted zero-argument fixtures, validates
structured failures against the published schema and records the runtime hash,
platform, capabilities and limits. Parsing, loading and execution are separate
claims. The vec2 signature fixture is load-only; it is not a zero-argument boot.
The fixed 194-byte minimal image comes from the independent runtime test oracle.
Synthetic common IR additionally exercises linking, lowering, optimization and
emission without PBS. Frontend migration and integrated release readiness are
tracked separately in AGD75; passing common conformance does not claim complete
PBS lowering or complete Studio/runtime integration.
@@ -0,0 +1,136 @@
# PBS input and existing value runtime alignment
Status: normative. Owner: `compiler/pbs`. Common ABI authority:
[typed Registry/PBX](../../general/specs/typed-registry-and-pbx-v0.md) and
[runtime catalogs](../../general/specs/runtime-catalog-support.md).
## Source types and exact carriers
| PBS source | Runtime identity | Ordered slots |
| --- | --- | --- |
| `int` | Int32 | Int32 |
| `long` | Int64 | Int64 |
| `float` | Float | Float (binary64) |
| `bool` | Bool | Bool |
| `str` | String | String |
| builtin `color` shell | color | Int64 constrained to RGBA8888 |
| builtin `vec2` shell | vec2 | Float x, Float y |
| builtin `pixel` shell | pixel | Int64 x, Int64 y, Int64 color |
The canonical builtin metadata determines a shell's identity; its source name
is not an ABI lookup rule. Equal widths do not permit substitution. Function
metadata MUST declare ordered parameter and result identities. Slot counts are
checked caches derived from those identities. Calls, locals and returns MUST
preserve entire value groups. A vec2 is one logical value with two slots;
a named output tuple is a fixed sequence of logical results, not a heap object.
`int` and `long` are distinct. Integer literals default to `int`; explicit
`long` contexts (annotations, parameters and results) validate literals in the
Int64 range and materialize them with that carrier. Out-of-range literals MUST
be diagnosed, never replaced by zero. A typed variable does not change type
because it appears in another expected context. Mixed int/long operations
require an explicit conversion. Existing `as` syntax expresses conversion:
```pbs
let frames: long = 2147483648;
let offset: int = 10;
let wide = offset as long;
let narrow = frames as int;
```
The final conversion faults if its value is outside Int32 range. Numeric
conversions use published math/mathf conversion intrinsics, without adding
math service facades. Int32/Int64 arithmetic preserves runtime wrapping;
Float overflow and range-invalid conversions preserve runtime faults.
Defaults are owned by the runtime storage contract: numeric zero, Float +0,
Bool false, nullable String null, transparent color, zero vec2 and zero pixel.
This does not introduce implicit source-variable initialization: VM locals
start null and PBS definite-assignment rules still apply. NaN/infinity are not
valid guest numeric defaults.
## Public input API
Import `Pad`, `Button` and `Touch` from `@sdk:input`. Button is a closed nominal
PBS enum with cases Up, Down, Left, Right, A, B, X, Y, L, R, Start and Select.
It identifies a button; it does not contain input state or perform a query.
Locals and typed function parameters may carry Button values, including values
selected during execution. Strings, integer indices and unrelated enums are
not valid Button arguments.
| Public operation | Result |
| --- | --- |
| `Pad.pressed(button: Button)` | bool |
| `Pad.released(button: Button)` | bool |
| `Pad.down(button: Button)` | bool |
| `Pad.hold(button: Button)` | long, held logical frames |
| `Touch.pressed()`, `Touch.released()`, `Touch.down()` | bool |
| `Touch.hold()` | long, held logical frames |
| `Touch.x()`, `Touch.y()` | long |
```pbs
import { Pad, Button, Touch } from @sdk:input;
fn jump(button: Button) -> bool {
return Pad.pressed(button);
}
fn held() -> long {
let jump_button = Button.A;
return Pad.hold(jump_button);
}
```
Pad dispatches to `LowPad.<button>_<query>()`, for example
`LowPad.a_pressed()`. All 48 combinations map to the published direct endpoint.
Each call MUST evaluate its selector once and execute exactly one chosen
query. It MUST NOT read unselected buttons, speculate input faults or collect
all button states. Constant specialization is optional; dynamic dispatch must
work without optimization.
All 54 VM queries take zero arguments and no receiver. Button never crosses
the intrinsic boundary as a selector. Touch x/y use current IDs 0x2134/0x2135
and Int64 results. No new device, button-state object, snapshot or multi-pad
contract is introduced. Known input without an available platform faults with
TRAP_UNAVAILABLE; it never fabricates false or zero. Unknown and retired IDs
are invalid even in unreachable code.
## Migration and diagnostics
The old Input root and intermediate InputPad/InputTouch/InputButton objects
are removed. Replace `Input.pad().a().pressed()` with
`Pad.pressed(Button.A)` and `Input.touch().x()` with `Touch.x()`.
`let button = Input.pad().a();` is invalid; `let button = Button.A;` is valid.
Migration diagnostics must point to the replacement surface. Hover, completion,
exports and examples must advertise the same API and exact return types.
When a consumer requires int coordinates, explicitly narrow a Touch result
with `as int`; do not silently change the query's ABI.
## Lowering and observable order
PBS owns source enum dispatch and typed metadata. Common code owns catalog
resolution, PBX validation and emission. The frontend MUST NOT maintain a
second intrinsic or constant catalog. SDK executable methods admit the existing
switch expression with value arms, apply and explicit numeric conversions
needed by this facade; other unsupported SDK constructs remain diagnosed.
For named application such as `f apply (y: effect_y(), x: effect_x())`, evaluate
Y then X exactly once, store complete groups in temporary locals, and reload
in x,y parameter order. Reordering expressions instead of values is invalid.
Builtin constants are groups resolved by the shared constant catalog.
`vec2.zero` materializes two Float slots; no intrinsic endpoint is invented.
Colors may use a published constant or an independently published intrinsic.
Function metadata must cover SDK wrappers such as Gfx.clear. Validation must
not infer missing identities from widths or omit the full installed example.
Preserve the existing lifecycle assembly and physical boot FunctionId zero.
## Conformance
The PBS source-to-production-PBX corpus and production runtime harness must
cover all 54 input queries with controlled input and exactly-one-query checks,
known-unavailable behavior, typed selectors, int/long boundaries and explicit
conversions, Float/String/Bool, color/vec2/pixel groups, multiple returns and
named-argument effects. Keep common registry wrong-carrier, retired-ID and stale
signature tests active. Record runtime hash, Studio revision, platform and
configuration. A catalog-only pass does not replace successful PBS execution
or `:prometeu-app:installedKnowledgeTest`.
@@ -296,3 +296,7 @@ This document is ready to move beyond temporary status only when:
2. diagnostic identity, metadata, and attribution rules are explicit enough for conformance, including locale-agnostic token/template identity, 2. diagnostic identity, metadata, and attribution rules are explicit enough for conformance, including locale-agnostic token/template identity,
3. the backend-originated failure boundary is explicit enough that PBS-facing diagnostics can be distinguished from internal tool failures, 3. the backend-originated failure boundary is explicit enough that PBS-facing diagnostics can be distinguished from internal tool failures,
4. and cost/warning expectations are explicit where they are intended to be normative for v1. 4. and cost/warning expectations are explicit where they are intended to be normative for v1.
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
@@ -238,3 +238,7 @@ At frontend `IRBackend` emission time:
4. module order in the declaration MUST propagate the explicit dependency order already derived from resolved project/module data, without sorting by `FileId`, textual module name, or synthetic callable name, 4. module order in the declaration MUST propagate the explicit dependency order already derived from resolved project/module data, without sorting by `FileId`, textual module name, or synthetic callable name,
5. PBS MUST NOT emit module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard, 5. PBS MUST NOT emit module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard,
6. and common lifecycle assembly remains the owner of derived artifacts, including the published wrapper that becomes the physical entrypoint and owns the final frame return. 6. and common lifecycle assembly remains the owner of derived artifacts, including the published wrapper that becomes the physical entrypoint and owns the final frame return.
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
@@ -48,7 +48,7 @@ Rules:
- `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source. - `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
- `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source. - `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
- A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner. - A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner.
- The builtin simple types `int`, `float`, `bool`, and `str` are always present in the type namespace. - The builtin simple types `int`, `long`, `float`, `bool`, and `str` are always present in the type namespace.
- Builtin simple types are resolved without import or declaration. - Builtin simple types are resolved without import or declaration.
- User-authored type declarations must not reuse builtin simple type names. - User-authored type declarations must not reuse builtin simple type names.
@@ -874,3 +874,7 @@ At minimum, deterministic static diagnostics are required for:
- invalid optional intrinsic member call, - invalid optional intrinsic member call,
- invalid builtin intrinsic member call, - invalid builtin intrinsic member call,
- member projection on a missing named output label. - member projection on a missing named output label.
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
@@ -537,3 +537,22 @@ The current PBS design direction is:
10. `declare host` remains reserved to stdlib/toolchain interface modules. 10. `declare host` remains reserved to stdlib/toolchain interface modules.
11. Reserved attributes such as `[Host(...)]` are compile-time metadata, not runtime objects. 11. Reserved attributes such as `[Host(...)]` are compile-time metadata, not runtime objects.
12. The compiler consumes `Host` metadata to produce runtime-facing host-binding artifacts defined elsewhere. 12. The compiler consumes `Host` metadata to produce runtime-facing host-binding artifacts defined elsewhere.
## Editorial exposure of external sources
SDK/core remain reserved bundled sources. Editorial navigation MUST NOT extract
or copy them into a project or disk cache. Compiler-known dependency sources,
including those under `.workspace`, and SDK/core are exposed as read-only external
documents with revision-consistent text, ranges and frontend semantic context.
Hover and continued definition use that retained context. Compilation, module
admission, ABI and linking rules are unchanged. See Compiler Spec 23 §8.3 and
Studio Spec 11 for the consumer protocol and atomic write restrictions (DEC-0062).
PBS project hover, definition, completion and signature help MUST share receiver
type resolution using PBS expression parsing and semantic overload rules. Coverage
includes function/method chains with known return types, nested call arguments,
explicitly typed and inferred variables, parentheses, completion after a trailing
dot and signature help during incomplete arguments. An unrelated parse error MUST
NOT invalidate a recoverable receiver. Unknown or ambiguous receivers MUST NOT
invent a type or overload. Indexing/operator-produced receivers are outside the
new coverage; existing behavior MUST NOT regress.
@@ -263,13 +263,13 @@ Example:
```pbs ```pbs
[BuiltinType(name="color", version=1)] [BuiltinType(name="color", version=1)]
declare builtin type Color( declare builtin type Color(
pub raw: int, pub raw: long,
); );
[BuiltinType(name="pixel", version=1)] [BuiltinType(name="pixel", version=1)]
declare builtin type Pixel( declare builtin type Pixel(
pub x: int, pub x: long,
pub y: int, pub y: long,
pub color: Color, pub color: Color,
); );
``` ```
@@ -277,13 +277,13 @@ declare builtin type Pixel(
Canonical semantic layout: Canonical semantic layout:
```text ```text
Pixel -> [int, int, Color] Pixel -> [long, long, Color]
``` ```
Canonical flattened slot layout: Canonical flattened slot layout:
```text ```text
Pixel -> [int, int, int] Pixel -> [long, long, long]
``` ```
## 13. Member Categories ## 13. Member Categories
@@ -560,3 +560,7 @@ The current temporary contract is:
7. `BuiltinConst(target, name, version)` exposes VM-owned builtin constants through reserved top-level `declare const` shells. 7. `BuiltinConst(target, name, version)` exposes VM-owned builtin constants through reserved top-level `declare const` shells.
8. Builtin projections, constants, and intrinsic calls must not lower through `SYSC`, `HOSTCALL`, or `SYSCALL`. 8. Builtin projections, constants, and intrinsic calls must not lower through `SYSC`, `HOSTCALL`, or `SYSCALL`.
9. Runtime-facing intrinsic artifacts are distinct from host-binding artifacts. 9. Runtime-facing intrinsic artifacts are distinct from host-binding artifacts.
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
@@ -323,3 +323,46 @@ The current Studio direction is:
4. the compiler should use explicit abstractions such as `StdlibEnvironment` and `StdlibModuleResolver`, 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, 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. 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.
## Editorial exposure of external sources
SDK/core remain reserved bundled sources. Editorial navigation MUST NOT extract
or copy them into a project or disk cache. Compiler-known dependency sources,
including those under `.workspace`, and SDK/core are exposed as read-only external
documents with revision-consistent text, ranges and frontend semantic context.
Hover and continued definition use that retained context. Compilation, module
admission, ABI and linking rules are unchanged. See Compiler Spec 23 §8.3 and
Studio Spec 11 for the consumer protocol and atomic write restrictions (DEC-0062).
@@ -387,3 +387,7 @@ This document is ready to move beyond temporary draft status only when:
3. host-call interaction rules are stated without relying on informal prose elsewhere, 3. host-call interaction rules are stated without relying on informal prose elsewhere,
4. the document can drive runtime conformance tests without decision backfill, 4. the document can drive runtime conformance tests without decision backfill,
5. the remaining TODO items are reduced to editorial integration rather than semantic uncertainty. 5. the remaining TODO items are reduced to editorial integration rather than semantic uncertainty.
## Existing values and input runtime alignment
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
@@ -2,6 +2,73 @@
This directory contains the normative PBS specification set. 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 ## Purpose
Specs define the official PBS language/frontend contract. Specs define the official PBS language/frontend contract.
@@ -1,5 +1,10 @@
# Bytecode and PBX Mapping Specification # Bytecode and PBX Mapping Specification
The current typed Registry/PBX v0 contract is normative in
[Typed common Registry and PBX v0](../../compiler/general/specs/typed-registry-and-pbx-v0.md).
Its complete typed function records, mandatory sections and verification rules
replace the earlier slot-only artifact baseline.
Status: Draft v1 (Backend Baseline) Status: Draft v1 (Backend Baseline)
Applies to: mapping from lowered/optimized backend programs into PBX sections, bytecode-facing artifacts, and source-to-artifact invariants required by loader/verifier/runtime Applies to: mapping from lowered/optimized backend programs into PBX sections, bytecode-facing artifacts, and source-to-artifact invariants required by loader/verifier/runtime
@@ -74,7 +79,8 @@ Emitter output must map to a `BytecodeModule` shape containing:
3. `code`, 3. `code`,
4. `exports`, 4. `exports`,
5. `syscalls`, 5. `syscalls`,
6. optional `debug_info` that still satisfies v1 minimum debug obligations. 6. typed Registry declarations, implementations and per-function capture lists,
7. optional `debug_info` that still satisfies v1 minimum debug obligations.
### 6.2 Function ordering and IDs ### 6.2 Function ordering and IDs
@@ -168,7 +174,6 @@ At minimum, artifact conformance checks should assert:
The following remain deferred: The following remain deferred:
- richer optional debug/source-map formats, - richer optional debug/source-map formats,
- additional PBX section-level contracts beyond current baseline,
- and profile-specific binary compatibility policy details beyond current v1 baseline. - and profile-specific binary compatibility policy details beyond current v1 baseline.
## 11. Non-Goals ## 11. Non-Goals
@@ -1,5 +1,10 @@
# Compiler Verification and Safety Checks Specification # Compiler Verification and Safety Checks Specification
The current typed Registry/PBX v0 contract is normative in
[Typed common Registry and PBX v0](../../compiler/general/specs/typed-registry-and-pbx-v0.md).
Its complete typed function records, mandatory sections and verification rules
replace the earlier slot-only artifact baseline.
Status: Draft v1 (Quality-Gate Baseline) Status: Draft v1 (Quality-Gate Baseline)
Applies to: test-backed safety gates for common compiler stages, validation ownership across executable frontends, and integration regression safety checks against runtime Applies to: test-backed safety gates for common compiler stages, validation ownership across executable frontends, and integration regression safety checks against runtime
@@ -1,5 +1,10 @@
# IRBackend to IRVM Lowering Specification # IRBackend to IRVM Lowering Specification
The current typed Registry/PBX v0 contract is normative in
[Typed common Registry and PBX v0](../../compiler/general/specs/typed-registry-and-pbx-v0.md).
Its complete typed function records, mandatory sections and verification rules
replace the earlier slot-only artifact baseline.
Status: Draft v1 (Backend Baseline) Status: Draft v1 (Backend Baseline)
Applies to: executable-backend lowering from the common `IRBackend` handoff into `IRVM` Applies to: executable-backend lowering from the common `IRBackend` handoff into `IRVM`
@@ -1,5 +1,10 @@
# Backend Spec-to-Test Conformance Matrix # Backend Spec-to-Test Conformance Matrix
The current typed Registry/PBX v0 contract is normative in
[Typed common Registry and PBX v0](../../compiler/general/specs/typed-registry-and-pbx-v0.md).
Its complete typed function records, mandatory sections and verification rules
replace the earlier slot-only artifact baseline.
Status: Draft v1 (Traceability Baseline) Status: Draft v1 (Traceability Baseline)
Applies to: compiler/backend conformance traceability for canonical stage order and entrypoint-specific contracts Applies to: compiler/backend conformance traceability for canonical stage order and entrypoint-specific contracts
@@ -140,3 +145,19 @@ Matrix integrity is enforced by automated document lint:
- if `PROMETEU_MATRIX_HARD_GATE=true` and `PROMETEU_CHANGED_FILES` contains a path under conformance-relevant FE/BE prefixes, - if `PROMETEU_MATRIX_HARD_GATE=true` and `PROMETEU_CHANGED_FILES` contains a path under conformance-relevant FE/BE prefixes,
- then this matrix file MUST be present in `PROMETEU_CHANGED_FILES`, otherwise the gate fails. - then this matrix file MUST be present in `PROMETEU_CHANGED_FILES`, otherwise the gate fails.
- CI policy uses strict Gate I mode via `PROMETEU_GATE_I_STRICT=true` (or `CI=true`) and requires `PROMETEU_RUNTIME_CHECK_CMD` for runtime-backed evidence. - CI policy uses strict Gate I mode via `PROMETEU_GATE_I_STRICT=true` (or `CI=true`) and requires `PROMETEU_RUNTIME_CHECK_CMD` for runtime-backed evidence.
## 7. Typed Registry/PBX v0 qualification (2026-10-14)
Owner: compiler/general. These rows supersede slot-only PBX coverage claims;
frontend syntax and lowering remain consumer-owned.
| Requirement | Evidence | Status | Scope |
| --- | --- | --- | --- |
| Stable declarations, nominal identity, structural deduplication and cycles | LinkedRegistryTest; IRBackendExecutableContractTest | pass | Common API and linking |
| Complete typed signatures, captures, roles and implementations | PbxRegistryConformanceTest; TypedCommonPipelineTest | pass | Common IR through emission |
| Exact PBX mandatory tables and multi-slot signatures | Independent 194-byte oracle; fixed vec2 function bytes | pass | Wire format, not a self round-trip |
| Runtime final admission and execution | tools/pbx-conformance/run.py | pass | Closure, trait, array, Dynamic, intrinsic, roles, joins, native binding; vec2 load-only |
| Invalid structures, references, code and resource refusal | tools/pbx-conformance/main.rs mutation corpus | pass | Production loader, default/lowered limits |
| Structured initialization and binding diagnostics | HeadlessProcessSessionTest; observed runtime JSON fixtures | pass | Preserves full payload through MCP, including null outer PC |
| Published schema covers current runtime reasons | Actual LifecycleRole/NonFiniteValue payloads against runtime schema | partial | Runtime enum/schema mismatch recorded in AGD75; no payload rewriting |
| PBS migration and integrated delivery | AGD75 and consumer tickets | partial | Existing PBS suite passing is not complete executable lowering evidence |
@@ -272,7 +272,17 @@ Absent editor capabilities MUST have deterministic fallback behavior at tooling
3. host protocols that can represent unsupported operations SHOULD do so explicitly; 3. host protocols that can represent unsupported operations SHOULD do so explicitly;
4. and absent editor capability MUST NOT be reported as a compiler failure. 4. and absent editor capability MUST NOT be reported as a compiler failure.
When a frontend exposes definition or navigation, each returned location MUST identify a compiler-known physical source file. A resolved symbol without a physical file MUST produce an empty definition response. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability. When a frontend exposes definition or navigation, each returned location MUST identify a compiler-known source in the analyzed revision. Editable main-project locations use `file:`. Bundled SDK/core and ordinary dependency sources use server-issued `prometeu-source:` identities for consumers that negotiate external-source support. Ownership, not physical containment or `SourceKind.PROJECT`, determines editability. Clients without support receive only editable physical project destinations; absent frontend support retains the empty fallback. This explicitly supersedes the earlier physical-only definition policy (DEC-0062).
`FrontendLanguageService.supportsExternalSources` and `sourceDocument` are optional,
with false/empty defaults. `FrontendDefinitionLocation.source`, when present,
contains the known source's exact text, origin, name, language, read-only ownership
and opaque frontend context. Compiler contracts do not mint session URIs; that is
the project host's responsibility. The content digest is not an SDK version.
External source snapshots MUST retain the exact analyzed text, source origin and frontend semantic context together. Declaration offsets and UTF-16 protocol positions MUST be calculated from that text. The frontend owns hover and continued definition inside external documents; adapters MUST NOT resolve language semantics. SDK/core MUST remain bundled without editorial extraction. Unknown, expired, unreadable or unauthorized identities MUST report unavailable without arbitrary path fallback.
External URIs are scoped to a project-server session and a content revision, not an SDK semantic version. A project-owned registry retains snapshots per consumer, independently of transport connections. Last release or project shutdown releases text and semantic context together. Reconnection MUST revalidate before queries resume; changed revisions require fresh navigation, never old positions applied to new text. One consumer closing MUST NOT invalidate another. All edit proposals touching an external source, including physical aliases, MUST be refused atomically. References, workspace symbols, document links and hierarchies retain their existing physical scopes; external navigation does not expand them.
When a frontend exposes find-references, each returned usage or declaration location MUST identify a compiler-known physical source file. A cursor offset whose definition response is empty MUST produce an empty references response. Host `includeDeclaration` MAY add the canonical declaration location only when that declaration is a compiler-known physical source file; it MUST NOT invent a virtual, untitled, or synthetic location. When a frontend exposes find-references, each returned usage or declaration location MUST identify a compiler-known physical source file. A cursor offset whose definition response is empty MUST produce an empty references response. Host `includeDeclaration` MAY add the canonical declaration location only when that declaration is a compiler-known physical source file; it MUST NOT invent a virtual, untitled, or synthetic location.
@@ -6,7 +6,7 @@ Purpose: Define the normative shell structure of the Studio UI.
## Authority and Precedence ## 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 ## Normative Inputs
@@ -46,10 +46,13 @@ The baseline workspace set includes:
- Asset Management; - Asset Management;
- Debugger/Profiler; - Debugger/Profiler;
- DEV, for granting/reclaiming project control and observing external-agent automation;
- Shipper, temporarily represented by the current `BuilderWorkspace`. - 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. `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 ## Workspace Architecture Model
The shell-level workspace host exists to mount independently authored workspaces under one Studio contract. The shell-level workspace host exists to mount independently authored workspaces under one Studio contract.
@@ -139,3 +142,23 @@ This specification is complete enough when:
- workspace and shell responsibilities are clearly separated; - workspace and shell responsibilities are clearly separated;
- the shell-level expectations for workspace architecture are explicit; - the shell-level expectations for workspace architecture are explicit;
- the baseline Studio frame is stable enough for implementation planning. - the baseline Studio frame is stable enough for implementation planning.
## Project Assistant Preparation (DEC-0061)
Project creation MUST scaffold neutral agent-integration intent in
`.studio/setup.json` and invoke the same preparation port used by existing
projects in DEV. Application infrastructure resolves installed Studio and client
configuration; the wizard/Core MUST NOT serialize provider TOML or launch an
agent. Failed preparation leaves a usable project with actionable incomplete
readiness in DEV, never a false ready claim. Runtime/editor settings and unrelated
client configuration MUST survive. Preparation grants no project control.
### Automatic preparation when opening a project
Opening a project MUST prepare its enabled MCP integration using the same neutral
port as scaffold and DEV retry. Desktop composition MUST start the shared loopback
server before project sessions become available; no external command or separate
per-project desktop Run is required. Explicitly disabled integration MUST remain
disabled. Preparation failure MUST remain visible in DEV readiness without blocking
project use. Opening MUST NOT publish credentials or grant/acquire agent control.
The coding client continues to own its configured stdio process and initial trust.
@@ -0,0 +1,401 @@
# 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.
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.
## 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;
- **Prepare assistant**, 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.
Preparation MUST report missing installation or configuration conflicts explicitly; it does not depend on a live grant or fabricate endpoint credentials. 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 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
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 |
| 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.
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
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 desktop MUST host Streamable HTTP at `127.0.0.1:<OS-assigned-port>/mcp`.
DEC-0061 adds Studio-owned stdio discovery and one-time preparation as specified
in spec 11. Each human grant publishes a fresh project-scoped credential through
the required lifecycle participant in spec 8. Authentication, project scope and
task identity remain separate checks. There is no global credential bypass.
Restart invalidates old access and requires a fresh human grant, while the native
client's command/configuration remains unchanged. No remote binding, accounts or
OAuth are introduced. Preparation never grants editing authority.
| Tool group | Required capabilities | Required authority |
| --- | --- | --- |
| Context/references | Project identity, languages, versions, capabilities and paginated references | Project credential; no acquired task 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 and network runtime discovery. Studio-owned stdio and local Codex preparation are the explicit DEC-0061 additions.
- 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.
## Integrated Connection Revision (DEC-0061)
Connection and authority MUST be displayed separately. Initialization/ping
liveness determines connection, while Core determines waiting/working/manual
control. A missing descriptor means waiting for access, not proof that Studio is
closed. Preparation reports initial client trust/reload requirements without
modifying approval policy. Revocation removes published access even before
asynchronous worker/runtime cleanup finishes. New grants never restore old task
IDs or receipts. Full integrated native-client acceptance belongs to PLN-0140;
the prior HTTP acceptance alone is insufficient.
@@ -0,0 +1,616 @@
# 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 the integrated connection revision in DEC-0061 (PLN-0140). 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:
HTTP `tools/list` MUST expose only composed handlers, never placeholder implementations. The offline Studio stdio entry MUST advertise the packaged catalog and report unavailable live capabilities explicitly.
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 desktop start generates a new instance identity. Each human project grant
publishes a fresh 256-bit bearer credential scoped to that canonical project root.
Every HTTP request MUST include `Authorization: Bearer <credential>`; missing,
wrong or revoked credentials return 401. Initialized HTTP sessions MUST be bound
to that credential/root; mixing another credential with an existing session returns
403. All tools, including knowledge reads, MUST enforce the authenticated root
before dispatch. No instance-wide credential bypass is permitted.
There is no query-string token, OAuth, cookie authentication, remote bind option
or wildcard listener. The endpoint has no query parameters. Studio also provides
its own stdio mode, described below; it is part of the same artifact.
Native clients may omit `Origin`. If present, it MUST exactly equal the live
endpoint's origin (`http://127.0.0.1:<port>`); `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. The project discovery file is the only secret-bearing setup output; persistent client configuration and clipboard assistance MUST NOT export 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.
### 1.1 Integrated Studio Entry and Offline Catalog
`StudioLauncher mcp --project <absolute-root>` MUST dispatch before JavaFX or
Spring desktop startup. The root MUST be canonicalized once, contain the project
manifest and remain bound for the process lifetime, independently of client cwd.
The mode MUST NOT open a desktop, LSP, runtime or another HTTP listener. It uses
newline-framed UTF-8 JSON-RPC on stdin/stdout; stdout is protocol-only. Requests
are bounded to 1 MiB. EOF closes transport resources without releasing task control.
Initialize, initialized notification, ping and tools/list MUST work before the
desktop, descriptor or grant exists. Offline descriptors come from the same
packaged catalog as HTTP. A deterministic fingerprint covers protocol and tool
schemas. Before forwarding, the connector MUST validate the descriptor, initialize
HTTP, check instance/root/fingerprint metadata, and compare live descriptors with
the packaged catalog. Missing handlers return unsupported capability; incompatible
protocol/schema fails explicitly rather than silently changing the client's tools.
Tool calls MUST preserve structuredContent, text/error blocks and native image
blocks. Response bounds MUST support images above the 1 MiB request limit; the
current response cap is 32 MiB, including a bounded body-read deadline. Network
redirects MUST NOT be followed. The connector MUST reject another project root.
Discovery runs on calls and bounded background checks. Missing publication means
waiting for access, not proof that the desktop is closed. Distinguish invalid
file/permissions, stale credentials/instance, catalog incompatibility and transport
reconnection. Calls cannot wait indefinitely for a grant. No reconnect path may
resubmit a tool call. An uncertain response MUST retain available clientRequestId
correlation and instruct receipt lookup within the same authorized task. A new
desktop/task has no old receipt registry and requires a fresh human grant.
### 1.2 Stable Installation and Project Preparation
The initial delivery targets Codex on macOS. Studio owns a versioned installation
under `~/Library/Application Support/Prometeu/Studio`, with an atomic `current`
reference. Each version includes `lib` dependencies and a compatible Java runtime
under `runtime`. Validate a staged version before switching `current`; retain
previous versions for rollback and already-running processes. Failed validation
MUST leave the existing reference intact. Registered commands MUST work without
an interactive shell PATH, external JDK or developer checkout.
The client command is the absolute `current/runtime/bin/java`, with argument-array
values `-cp`, `<current>/lib/*`, `p.studio.app.StudioLauncher`, `mcp`, `--project`,
and the canonical root. No project-local executable, generated transport script,
helper binary or separate launcher installation is allowed. The desktop and
connector use the same Studio artifact. JDWP is an explicit development-only JVM
option; IntelliJ attaches to the client-owned connector process separately from
the desktop Debug configuration.
New-project scaffolding and existing-project preparation MUST use the same neutral
preparation port. `.studio/setup.json` stores integration schema/enabled/profile
intent, preserving runtime/editor settings; it contains no endpoint/credential/task.
Application infrastructure owns `.codex/config.toml` serialization. Its managed
`mcp_servers.prometeu_studio` table stores the stable command, arguments, project
cwd and cold-start timeout. Preserve all unrelated tables, comments, approval
policy and server entries byte-for-byte; validate edits with a TOML parser.
Repetition with identical values MUST be a no-op. User-owned or modified managed
entries and tracked client configuration MUST produce an actionable conflict,
never an overwrite. Keep a protected recovery copy of the previous owned block
without copying unrelated secrets. Precise ignore rules protect machine-local
client configuration and transient discovery without deleting existing rules.
Preparation MUST report incomplete writes/installations truthfully. Trust/reload
instructions apply to initial client registration only; no client trust or tool
approval may be bypassed. Grant and desktop restart MUST NOT require changing the
client configuration. A clone is prepared locally to resolve its own installation
and project paths. No global client configuration is rewritten.
### 1.3 DEV Connection Assistance
DEV MUST expose preparation/readiness through neutral API contracts and show
connection status separately from Core authority. Waiting for access, connected
and reconnecting derive from project-scoped initialization/ping activity with a
bounded liveness window; a retained HTTP session ID alone is insufficient. Working
remains an authority/operation state. DEV MUST NOT invent knowledge of a client
before it connects. A transport drop MUST NOT revoke a task or grant new control.
Preparation, labels, clipboard, diagnostics and history MUST NOT expose secrets.
Closing/hiding DEV only unsubscribes visual listeners. Human grant/reclaim and
project/application teardown retain their shared Core semantics. Instructions
cover native file edits, project knowledge, grant/acquire, validation, receipt
lookup, images and explicit release without generated transport clients.
## 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
need no acquired task. HTTP access still requires the project credential published by human grant. Offline catalog discovery returns no task token.
- `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.
### 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 physical 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 or to an external identity owned by the current task and project.
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. `readExternalSource` reads the exact registered external
revision; hover and definition on its URI use the retained frontend semantic
context. Indexed SDK reference tools remain separate and available. MCP needs no
VS Code connection and MUST retain its consumer across short-lived query sockets.
Task return/cancellation releases that task's external uses; project shutdown
invalidates all identities. Cross-task/project replay is refused.
### External-source protocol (DEC-0062)
Initialize negotiates `capabilities.experimental.prometeuExternalSources: true`;
the server advertises the same flag only when supported. External definitions use
`prometeu-source:` URIs minted by the project host. A descriptor carries `uri`,
`revision` (content digest), `origin`, `name`, `languageId` and `readOnly: true`.
Locations carry ordinary LSP UTF-16 ranges over that exact source text.
The `prometeu/readExternalSource`, `prometeu/retainExternalSource`,
`prometeu/releaseExternalSource` and `prometeu/revalidateExternalSource` requests
carry `uri` and a server-issued `consumerId`. Initialize returns that identity in
`capabilities.experimental.prometeuExternalConsumerId`. Reconnecting clients pass
it as `initializationOptions.prometeuExternalConsumerId`; MCP also requests
`initializationOptions.prometeuExternalPersistentConsumer: true` on first use.
`releaseExternalSource` with `uri: null` releases the consumer and all its sources.
A read or explicit retain acknowledges a navigation result; unacknowledged results
are released when the socket closes. MCP acknowledges returned definitions before
closing its query connection and rolls back newly retained results on failure.
Read-only edit refusal uses LSP error `-32010`, mapped to MCP `READ_ONLY_SCOPE`.
Consumer identity is scoped to the
project session; the MCP adapter additionally binds it to its authorized task.
Read returns the descriptor plus `text`. Retain/release are idempotent per consumer.
Revalidation confirms the same admitted origin and revision before queries resume;
a changed revision reports unavailable and requires new navigation. Unknown,
expired, unauthorized and unreadable sources are explicit errors, never disk reads
chosen by client paths. Consumers are created by the server, not caller-selected.
VS Code uses a read-only text content provider, with the source language and no
save-back path. Disconnect may leave the immutable text visible, but blocks
semantic queries until revalidation. No content-change event may replace the old
revision under old positions. Closing the last consumer releases the snapshot;
one reader closing must not invalidate another reader. Edit operations and mixed
workspace edits are rejected in their entirety, including physical aliases.
Packaged Studio validation is excluded from this delivery; development tests must
exercise both VS Code and independent MCP navigation.
## 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.
### 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.
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
disconnect nor polling silence discards an authorized task's records.
## 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 reference content is resolved through the frontend's owner-maintained
reference provider, not a Studio-maintained language specification.
### 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 acquire task authority. The HTTP boundary separately requires the grant-published project credential. 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.
### 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 (`<languageId>:`), 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 an acquired task; the transport still requires a grant-published project credential. 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
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 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
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.
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.
The former configuration-copy flow is superseded by DEC-0061 permanent preparation and grant-time discovery. 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. 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.
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. The historical probe of the former SDK `Input.pad()` definition returned
an empty result (the current facade is Pad/Button and Touch); 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.
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. 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.
### Integrated Connection Acceptance (DEC-0061)
Prior DSC-0068 native-client evidence covers the original HTTP flow only. The
integrated flow additionally requires a real native Codex session initialized
before grant, unchanged configuration through desktop restart/new grant, native
images/build/release, scaffold and existing-project preparation, installation
update and graphical launch, plus IntelliJ connector attachment. Automated
fixtures cannot substitute for these gates. PLN-0140 completed automated validation
and the user confirmed all outstanding manual gates on 2026-09-29. The manual
confirmation is user-reported acceptance, not an independently observed test run.
[LSN-0077](../../../discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md)
preserves the result and evidence provenance after workflow housekeeping.
### Automatic preparation when opening a project
Opening a project MUST prepare its enabled MCP integration using the same neutral
port as scaffold and DEV retry. Desktop composition MUST start the shared loopback
server before project sessions become available; no external command or separate
per-project desktop Run is required. Explicitly disabled integration MUST remain
disabled. Preparation failure MUST remain visible in DEV readiness without blocking
project use. Opening MUST NOT publish credentials or grant/acquire agent control.
The coding client continues to own its configured stdio process and initial trust.
@@ -79,6 +79,8 @@ The main session-restoration store MUST NOT include:
- heavy operational output; - heavy operational output;
- recomputable results that do not represent session restoration state. - 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 for every project grant and never restored on 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. `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 ## Ownership Rules
@@ -103,3 +105,36 @@ This specification is complete enough when:
- accepted and excluded categories are explicit; - accepted and excluded categories are explicit;
- load, restore, save, and fallback timing are explicit; - load, restore, save, and fallback timing are explicit;
- and the ownership boundary with `StudioProjectSession` is normatively locked. - and the ownership boundary with `StudioProjectSession` is normatively locked.
## Integrated MCP Discovery (DEC-0061)
`.studio/setup.json` MUST carry neutral `agentIntegration` intent with
`schemaVersion:1`, `enabled` and `clientProfile`. Preserve runtime and editor
fields. This intent is configuration, not readiness or authorization. Machine-local
resolved client configuration is a separate preparation output.
The transient descriptor is `.studio/mcp/connection.json`, limited to 16 KiB.
Schema v1 requires integral `schemaVersion:1` and nonempty string `instanceId`,
`projectRoot`, `endpoint`, `credential`, `catalogFingerprint`. Root MUST match the
connector's canonical root. Endpoint MUST be `http://127.0.0.1:<port>/mcp`, with
no userinfo, query, fragment or redirect. Grant/task IDs and receipts are forbidden.
On macOS `.studio/mcp` MUST be owned by the current user with mode 0700;
descriptor, lock and temporary files MUST be 0600 before secrets are written.
Reject symlinked/unsafe paths and tracked descriptor targets. Add precise ignore
rules idempotently without changing unrelated project permissions or files.
Ownership MUST use an OS-held lock on the stable `publication.lock` inode; do
not delete the lock file on ordinary cleanup. A second live publisher fails. A
crashed process releases its lock through the OS; a new owner may atomically
replace stale content. Write a protected same-directory temporary file and
atomically rename it. Cleanup checks both instance and publication generation
so an old callback cannot remove newer discovery data.
Publication is a required grant lifecycle participant, not a swallowed observer.
Prepare/publish occur outside the Core monitor; authority activation uses a
generation fence. Acquisition cannot succeed until publication and grant both
commit. Failure aborts credentials/files and reports a failed grant. Revoke/close
invalidate credentials before asynchronous work cleanup, then remove owned
publication and release ownership. File cleanup failure MUST NOT prevent runtime
cancellation. An already-admitted release response MUST remain deliverable.
@@ -18,14 +18,16 @@ Define the physical and functional boundary that makes the Studio consumable by
## Authority and Precedence ## 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 ## Architectural Model
The Studio is a set of project and tooling services consumed by adapters: The Studio is a set of project and tooling services consumed by adapters:
```text ```text
JavaFX UI ──> Studio API <── future non-visual adapters JavaFX UI ──> Studio API <── local MCP adapter <── external coding agent
│ │
▼ ▼
Studio Core Studio Core
@@ -34,7 +36,7 @@ JavaFX UI ──> Studio API <── future non-visual adapters
application/infrastructure 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 ## Physical Modules
@@ -53,7 +55,8 @@ The public Studio API MUST be plain Java and MUST NOT depend on:
- JavaFX; - JavaFX;
- Spring Framework, Spring Boot, or Spring Modulith; - 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; - concrete compiler, Packer, LSP, or runtime implementations;
- `p.studio.core` or `p.studio.ui.javafx` internals. - `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: The core module MUST NOT:
- depend on JavaFX or UI packages; - depend on JavaFX or UI packages;
- depend on HTTP/MCP SDKs, Spring, or concrete external protocol DTOs;
- call `Platform.runLater`; - call `Platform.runLater`;
- perform navigation or workspace selection; - perform navigation or workspace selection;
- use presentation severity or visual state as domain semantics; - use presentation severity or visual state as domain semantics;
@@ -76,11 +80,11 @@ The core module MUST NOT:
The functional core modules are: The functional core modules are:
- `project`: project identity, catalog, creation, paths, setup, and restoration state; - `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; - `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; - `shipper`: build/pack coordination, manifest generation, artifacts, and neutral logs/results;
- `runtime`: runtime settings, handshake, process/client lifecycle, and technical logs; - `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 state, cancellation, shutdown, and orchestration of shipper and runtime. - `execution`: play/stop and automation operation state, cancellation, shutdown, and orchestration of shipper and runtime.
The functional dependency direction MUST remain: The functional dependency direction MUST remain:
@@ -92,6 +96,10 @@ execution --> project, shipper, runtime
session --> project, execution, LSP port 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 ## 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. 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 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:<OS-assigned-port>/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a fresh grant-published project credential, validate project/session scope and Origin, and stop with Studio. Connection authentication MUST NOT grant project/task authority. Credentials MUST NOT be stored in versioned files. Restart requires a fresh human grant, while the stable client configuration remains unchanged.
This exception does not authorize a web UI, remote binding, general-purpose web application, accounts or OAuth. DEC-0061 explicitly adds the Studio-owned stdio mode and local client preparation. 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. 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 | | `session` | LSP | Neutral session-owned lifecycle port |
| `runtime` | external runtime/process | Narrow runtime-owned gateway | | `runtime` | external runtime/process | Narrow runtime-owned gateway |
| JavaFX UI | Studio | Studio API only | | 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. `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,22 +153,42 @@ 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. 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 ## Conformance Gates
The architecture is conformant only when all of the following hold together: 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; - UI has no dependency on core or concrete external providers;
- `ApplicationModules.verify()` succeeds for the exclusive `p.studio.core` root; - `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; - `Container`, `AppContainer`, compatibility allowlists, and the mixed module are absent;
- unit, integration, architecture, packaging, and desktop smoke tests pass; - unit, integration, architecture, packaging, and desktop smoke tests pass;
- no service locator or context lookup replaces the removed static container. - no service locator or context lookup replaces the removed static container.
## Non-Goals ## 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; - replacing JavaFX with a web UI;
- migrating the Studio to Rust, Electron, Tauri, or a parallel rewrite; - migrating the Studio to Rust, Electron, Tauri, or a parallel rewrite;
- redesigning compiler, Packer, LSP, or runtime semantics; - redesigning compiler, Packer, LSP, or runtime semantics;
- introducing microservices or durable event infrastructure. - introducing microservices or durable event infrastructure.
## Integrated MCP Connection Boundary (DEC-0061)
The same Studio application artifact MUST support `mcp --project` over stdio
before desktop composition. It connects to the existing loopback HTTP adapter;
it MUST NOT implement separate authority, operations, language services or runtime
semantics. Offline catalog loading does not initialize the desktop graph.
API exposes neutral preparation/readiness and connection-publication lifecycle
ports. Core orchestrates save, publication commit/abort, grant, revocation and
shutdown through those ports. Application infrastructure owns credentials, file
locks/atomic discovery, HTTP identity checks, TOML preparation and managed
installation/runtime packaging. JavaFX consumes neutral status and actions only.
Filesystem publication MUST NOT run under a long-held authority monitor.
+20 -5
View File
@@ -56,6 +56,8 @@ The current Studio core corpus is:
4. [`4. Assets Workspace Specification.md`](4.%20Assets%20Workspace%20Specification.md) 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) 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) 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 ## Reading Order
@@ -66,7 +68,9 @@ Recommended order:
3. components module policy; 3. components module policy;
4. assets workspace behavior; 4. assets workspace behavior;
5. project-local Studio state 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;
8. MCP transport/tool schemas and project/language knowledge contracts.
## Current Wave Notes ## Current Wave Notes
@@ -74,9 +78,20 @@ The embedded Studio code-editor stack was removed by `DEC-0031`.
Normative reminders: 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`; - 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. - 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 the JavaFX adapter and future non-visual adapters; - the Studio backend is exposed through neutral API contracts shared by JavaFX and the local MCP adapter, without duplicated authority or orchestration;
- Spring Boot is a non-web composition root, while Spring Modulith verifies the JavaFX-free `p.studio.core` boundary; - 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. - `p.studio.Container`, `AppContainer`, and the mixed `prometeu-studio` module are not valid final architecture.
## Integrated MCP connection
DEC-0061 revises the baseline with Studio-owned `mcp --project` mode, grant-time
project discovery, scoped HTTP credentials, one-time scaffold/preparation and a
stable installation with bundled Java. Specs 8–11 define the lifecycle and
transport boundaries; spec 1 defines project creation. PLN-0140 is complete;
automated results and user-confirmed manual acceptance are consolidated in
[LSN-0077](../../../discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md).
The earlier HTTP evidence was not substituted for these gates. The embedded
terminal remains separate.
+17
View File
@@ -0,0 +1,17 @@
target,name,version,slot,carrier,bits_or_value
color,black,1,0,Int64,255
color,blue,1,0,Int64,65535
color,cyan,1,0,Int64,16777215
color,gray,1,0,Int64,2155905279
color,green,1,0,Int64,16711935
color,indigo,1,0,Int64,1258324735
color,magenta,1,0,Int64,4278255615
color,orange,1,0,Int64,4286578943
color,red,1,0,Int64,4278190335
color,transparent,1,0,Int64,0
color,white,1,0,Int64,4294967295
color,yellow,1,0,Int64,4294902015
mathf,pi,1,0,Float,0x400921FB54442D18
mathf,tau,1,0,Float,0x401921FB54442D18
vec2,zero,1,0,Float,0x0000000000000000
vec2,zero,1,1,Float,0x0000000000000000
1 target name version slot carrier bits_or_value
2 color black 1 0 Int64 255
3 color blue 1 0 Int64 65535
4 color cyan 1 0 Int64 16777215
5 color gray 1 0 Int64 2155905279
6 color green 1 0 Int64 16711935
7 color indigo 1 0 Int64 1258324735
8 color magenta 1 0 Int64 4278255615
9 color orange 1 0 Int64 4286578943
10 color red 1 0 Int64 4278190335
11 color transparent 1 0 Int64 0
12 color white 1 0 Int64 4294967295
13 color yellow 1 0 Int64 4294902015
14 mathf pi 1 0 Float 0x400921FB54442D18
15 mathf tau 1 0 Float 0x401921FB54442D18
16 vec2 zero 1 0 Float 0x0000000000000000
17 vec2 zero 1 1 Float 0x0000000000000000
+106 -43
View File
@@ -1,43 +1,106 @@
final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles,mutates_guest_state,cost_model,attempt_cost_cycles,max_attempts
0x1000,4096,vec2.dot,1,vec2,dot,4,1,float|float|float|float,float,true,false 0x1000,4096,vec2.dot,1,vec2,dot,4,1,Float|Float|Float|Float,Float,true,false,ax|ay|bx|by,10,false,fixed,0,0
0x1001,4097,vec2.length,1,vec2,length,2,1,float|float,float,true,false 0x1001,4097,vec2.length,1,vec2,length,2,1,Float|Float,Float,true,false,x|y,40,false,fixed,0,0
0x1100,4352,color.from_raw,1,color,from_raw,1,1,int,builtin:color,true,false 0x1100,4352,color.from_raw,1,color,from_raw,1,1,Int64,builtin:color,true,false,raw,1,false,fixed,0,0
0x1101,4353,color.rgb,1,color,rgb,3,1,int|int|int,builtin:color,true,false 0x1101,4353,color.rgb,1,color,rgb,3,1,Int64|Int64|Int64,builtin:color,true,false,r|g|b,1,false,fixed,0,0
0x1102,4354,color.rgba,1,color,rgba,4,1,int|int|int|int,builtin:color,true,false 0x1102,4354,color.rgba,1,color,rgba,4,1,Int64|Int64|Int64|Int64,builtin:color,true,false,r|g|b|a,1,false,fixed,0,0
0x1103,4355,color.html_rgba,1,color,html_rgba,1,1,str,builtin:color,true,false 0x1103,4355,color.html_rgba,1,color,html_rgba,1,1,String,builtin:color,true,false,value,1,false,fixed,0,0
0x1104,4356,color.gray_scale,1,color,gray_scale,1,1,int,builtin:color,true,false 0x1104,4356,color.gray_scale,1,color,gray_scale,1,1,Int64,builtin:color,true,false,value,1,false,fixed,0,0
0x1105,4357,color.hex,1,color,hex,1,1,builtin:color,int,true,false 0x1105,4357,color.hex,1,color,hex,1,1,builtin:color,Int64,true,false,color,1,false,fixed,0,0
0x1106,4358,color.alpha,1,color,alpha,1,1,builtin:color,int,true,false 0x1106,4358,color.alpha,1,color,alpha,1,1,builtin:color,Int64,true,false,color,1,false,fixed,0,0
0x1120,4384,color.black,1,color,black,0,1,,builtin:color,true,false 0x1120,4384,color.black,1,color,black,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1121,4385,color.white,1,color,white,0,1,,builtin:color,true,false 0x1121,4385,color.white,1,color,white,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1122,4386,color.red,1,color,red,0,1,,builtin:color,true,false 0x1122,4386,color.red,1,color,red,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1123,4387,color.green,1,color,green,0,1,,builtin:color,true,false 0x1123,4387,color.green,1,color,green,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1124,4388,color.blue,1,color,blue,0,1,,builtin:color,true,false 0x1124,4388,color.blue,1,color,blue,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1125,4389,color.yellow,1,color,yellow,0,1,,builtin:color,true,false 0x1125,4389,color.yellow,1,color,yellow,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1126,4390,color.orange,1,color,orange,0,1,,builtin:color,true,false 0x1126,4390,color.orange,1,color,orange,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1127,4391,color.indigo,1,color,indigo,0,1,,builtin:color,true,false 0x1127,4391,color.indigo,1,color,indigo,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1128,4392,color.gray,1,color,gray,0,1,,builtin:color,true,false 0x1128,4392,color.gray,1,color,gray,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x1129,4393,color.cyan,1,color,cyan,0,1,,builtin:color,true,false 0x1129,4393,color.cyan,1,color,cyan,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x112A,4394,color.magenta,1,color,magenta,0,1,,builtin:color,true,false 0x112A,4394,color.magenta,1,color,magenta,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x112B,4395,color.transparent,1,color,transparent,0,1,,builtin:color,true,false 0x112B,4395,color.transparent,1,color,transparent,0,1,,builtin:color,true,false,,1,false,fixed,0,0
0x2000,8192,input.pad,1,input,pad,0,1,,builtin:input.pad,true,false 0x2100,8448,input.pad.up.pressed,1,input.pad.up,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2001,8193,input.touch,1,input,touch,0,1,,builtin:input.touch,true,false 0x2101,8449,input.pad.up.released,1,input.pad.up,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2010,8208,input.pad.up,1,input.pad,up,1,1,builtin:input.pad,builtin:input.button,true,false 0x2102,8450,input.pad.up.down,1,input.pad.up,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2011,8209,input.pad.down,1,input.pad,down,1,1,builtin:input.pad,builtin:input.button,true,false 0x2103,8451,input.pad.up.hold,1,input.pad.up,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2012,8210,input.pad.left,1,input.pad,left,1,1,builtin:input.pad,builtin:input.button,true,false 0x2104,8452,input.pad.down.pressed,1,input.pad.down,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2013,8211,input.pad.right,1,input.pad,right,1,1,builtin:input.pad,builtin:input.button,true,false 0x2105,8453,input.pad.down.released,1,input.pad.down,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2014,8212,input.pad.a,1,input.pad,a,1,1,builtin:input.pad,builtin:input.button,true,false 0x2106,8454,input.pad.down.down,1,input.pad.down,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2015,8213,input.pad.b,1,input.pad,b,1,1,builtin:input.pad,builtin:input.button,true,false 0x2107,8455,input.pad.down.hold,1,input.pad.down,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2016,8214,input.pad.x,1,input.pad,x,1,1,builtin:input.pad,builtin:input.button,true,false 0x2108,8456,input.pad.left.pressed,1,input.pad.left,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2017,8215,input.pad.y,1,input.pad,y,1,1,builtin:input.pad,builtin:input.button,true,false 0x2109,8457,input.pad.left.released,1,input.pad.left,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2018,8216,input.pad.l,1,input.pad,l,1,1,builtin:input.pad,builtin:input.button,true,false 0x210A,8458,input.pad.left.down,1,input.pad.left,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2019,8217,input.pad.r,1,input.pad,r,1,1,builtin:input.pad,builtin:input.button,true,false 0x210B,8459,input.pad.left.hold,1,input.pad.left,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x201A,8218,input.pad.start,1,input.pad,start,1,1,builtin:input.pad,builtin:input.button,true,false 0x210C,8460,input.pad.right.pressed,1,input.pad.right,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x201B,8219,input.pad.select,1,input.pad,select,1,1,builtin:input.pad,builtin:input.button,true,false 0x210D,8461,input.pad.right.released,1,input.pad.right,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2020,8224,input.touch.button,1,input.touch,button,1,1,builtin:input.touch,builtin:input.button,true,false 0x210E,8462,input.pad.right.down,1,input.pad.right,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2021,8225,input.touch.x,1,input.touch,x,1,1,builtin:input.touch,int,true,false 0x210F,8463,input.pad.right.hold,1,input.pad.right,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2022,8226,input.touch.y,1,input.touch,y,1,1,builtin:input.touch,int,true,false 0x2110,8464,input.pad.a.pressed,1,input.pad.a,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2030,8240,input.button.pressed,1,input.button,pressed,1,1,builtin:input.button,bool,true,false 0x2111,8465,input.pad.a.released,1,input.pad.a,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2031,8241,input.button.released,1,input.button,released,1,1,builtin:input.button,bool,true,false 0x2112,8466,input.pad.a.down,1,input.pad.a,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2032,8242,input.button.down,1,input.button,down,1,1,builtin:input.button,bool,true,false 0x2113,8467,input.pad.a.hold,1,input.pad.a,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2033,8243,input.button.hold,1,input.button,hold,1,1,builtin:input.button,int,true,false 0x2114,8468,input.pad.b.pressed,1,input.pad.b,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2115,8469,input.pad.b.released,1,input.pad.b,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2116,8470,input.pad.b.down,1,input.pad.b,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2117,8471,input.pad.b.hold,1,input.pad.b,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2118,8472,input.pad.x.pressed,1,input.pad.x,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2119,8473,input.pad.x.released,1,input.pad.x,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x211A,8474,input.pad.x.down,1,input.pad.x,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x211B,8475,input.pad.x.hold,1,input.pad.x,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x211C,8476,input.pad.y.pressed,1,input.pad.y,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x211D,8477,input.pad.y.released,1,input.pad.y,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x211E,8478,input.pad.y.down,1,input.pad.y,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x211F,8479,input.pad.y.hold,1,input.pad.y,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2120,8480,input.pad.l.pressed,1,input.pad.l,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2121,8481,input.pad.l.released,1,input.pad.l,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2122,8482,input.pad.l.down,1,input.pad.l,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2123,8483,input.pad.l.hold,1,input.pad.l,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2124,8484,input.pad.r.pressed,1,input.pad.r,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2125,8485,input.pad.r.released,1,input.pad.r,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2126,8486,input.pad.r.down,1,input.pad.r,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2127,8487,input.pad.r.hold,1,input.pad.r,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2128,8488,input.pad.start.pressed,1,input.pad.start,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2129,8489,input.pad.start.released,1,input.pad.start,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x212A,8490,input.pad.start.down,1,input.pad.start,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x212B,8491,input.pad.start.hold,1,input.pad.start,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x212C,8492,input.pad.select.pressed,1,input.pad.select,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x212D,8493,input.pad.select.released,1,input.pad.select,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x212E,8494,input.pad.select.down,1,input.pad.select,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x212F,8495,input.pad.select.hold,1,input.pad.select,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2130,8496,input.touch.button.pressed,1,input.touch.button,pressed,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2131,8497,input.touch.button.released,1,input.touch.button,released,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2132,8498,input.touch.button.down,1,input.touch.button,down,0,1,,Bool,true,false,,1,false,fixed,0,0
0x2133,8499,input.touch.button.hold,1,input.touch.button,hold,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2134,8500,input.touch.x,1,input.touch,x,0,1,,Int64,true,false,,1,false,fixed,0,0
0x2135,8501,input.touch.y,1,input.touch,y,0,1,,Int64,true,false,,1,false,fixed,0,0
0x3000,12288,math.i32.min,1,math.i32,min,2,1,Int32|Int32,Int32,true,false,a|b,2,false,fixed,0,0
0x3001,12289,math.i32.max,1,math.i32,max,2,1,Int32|Int32,Int32,true,false,a|b,2,false,fixed,0,0
0x3002,12290,math.i32.clamp,1,math.i32,clamp,3,1,Int32|Int32|Int32,Int32,true,false,value|min|max,4,false,fixed,0,0
0x3003,12291,math.i32.abs,1,math.i32,abs,1,1,Int32,Int32,true,false,value,2,false,fixed,0,0
0x3004,12292,math.i64.min,1,math.i64,min,2,1,Int64|Int64,Int64,true,false,a|b,2,false,fixed,0,0
0x3005,12293,math.i64.max,1,math.i64,max,2,1,Int64|Int64,Int64,true,false,a|b,2,false,fixed,0,0
0x3006,12294,math.i64.clamp,1,math.i64,clamp,3,1,Int64|Int64|Int64,Int64,true,false,value|min|max,4,false,fixed,0,0
0x3007,12295,math.i64.abs,1,math.i64,abs,1,1,Int64,Int64,true,false,value,2,false,fixed,0,0
0x3008,12296,mathf.min,1,mathf,min,2,1,Float|Float,Float,true,false,a|b,2,false,fixed,0,0
0x3009,12297,mathf.max,1,mathf,max,2,1,Float|Float,Float,true,false,a|b,2,false,fixed,0,0
0x300A,12298,mathf.clamp,1,mathf,clamp,3,1,Float|Float|Float,Float,true,false,value|min|max,4,false,fixed,0,0
0x300B,12299,mathf.abs,1,mathf,abs,1,1,Float,Float,true,false,value,2,false,fixed,0,0
0x300C,12300,mathf.floor,1,mathf,floor,1,1,Float,Float,true,false,value,4,false,fixed,0,0
0x300D,12301,mathf.ceil,1,mathf,ceil,1,1,Float,Float,true,false,value,4,false,fixed,0,0
0x300E,12302,mathf.trunc,1,mathf,trunc,1,1,Float,Float,true,false,value,4,false,fixed,0,0
0x300F,12303,mathf.round,1,mathf,round,1,1,Float,Float,true,false,value,4,false,fixed,0,0
0x3010,12304,mathf.sqrt,1,mathf,sqrt,1,1,Float,Float,true,false,value,16,false,fixed,0,0
0x3011,12305,mathf.sin,1,mathf,sin,1,1,Float,Float,true,false,angle,32,false,fixed,0,0
0x3012,12306,mathf.cos,1,mathf,cos,1,1,Float,Float,true,false,angle,32,false,fixed,0,0
0x3013,12307,mathf.atan2,1,mathf,atan2,2,1,Float|Float,Float,true,false,y|x,48,false,fixed,0,0
0x3014,12308,math.i32.to_i64,1,math.i32,to_i64,1,1,Int32,Int64,true,false,value,2,false,fixed,0,0
0x3015,12309,math.i64.to_i32,1,math.i64,to_i32,1,1,Int64,Int32,true,false,value,2,false,fixed,0,0
0x3016,12310,math.i32.to_float,1,math.i32,to_float,1,1,Int32,Float,true,false,value,2,false,fixed,0,0
0x3017,12311,math.i64.to_float,1,math.i64,to_float,1,1,Int64,Float,true,false,value,2,false,fixed,0,0
0x3018,12312,mathf.to_i32,1,mathf,to_i32,1,1,Float,Int32,true,false,value,2,false,fixed,0,0
0x3019,12313,mathf.to_i64,1,mathf,to_i64,1,1,Float,Int64,true,false,value,2,false,fixed,0,0
0x4000,16384,random.new,1,random,new,1,1,Int64,builtin:Random,true,true,seed,32,true,fixed,0,0
0x4001,16385,random.next,1,random,next,1,1,builtin:Random,Int64,true,false,rng,8,true,fixed,0,0
0x4002,16386,random.nextf,1,random,nextf,1,1,builtin:Random,Float,true,false,rng,12,true,fixed,0,0
0x4003,16387,random.range,1,random,range,3,1,builtin:Random|Int64|Int64,Int64,true,false,rng|min|max,4,true,random_rejection_v1,8,64
1 final_id_hex final_id_dec canonical_name canonical_version owner name arg_slots ret_slots arg_layout ret_layout deterministic may_allocate parameter_names cost_cycles mutates_guest_state cost_model attempt_cost_cycles max_attempts
2 0x1000 4096 vec2.dot 1 vec2 dot 4 1 float|float|float|float Float|Float|Float|Float float Float true false ax|ay|bx|by 10 false fixed 0 0
3 0x1001 4097 vec2.length 1 vec2 length 2 1 float|float Float|Float float Float true false x|y 40 false fixed 0 0
4 0x1100 4352 color.from_raw 1 color from_raw 1 1 int Int64 builtin:color true false raw 1 false fixed 0 0
5 0x1101 4353 color.rgb 1 color rgb 3 1 int|int|int Int64|Int64|Int64 builtin:color true false r|g|b 1 false fixed 0 0
6 0x1102 4354 color.rgba 1 color rgba 4 1 int|int|int|int Int64|Int64|Int64|Int64 builtin:color true false r|g|b|a 1 false fixed 0 0
7 0x1103 4355 color.html_rgba 1 color html_rgba 1 1 str String builtin:color true false value 1 false fixed 0 0
8 0x1104 4356 color.gray_scale 1 color gray_scale 1 1 int Int64 builtin:color true false value 1 false fixed 0 0
9 0x1105 4357 color.hex 1 color hex 1 1 builtin:color int Int64 true false color 1 false fixed 0 0
10 0x1106 4358 color.alpha 1 color alpha 1 1 builtin:color int Int64 true false color 1 false fixed 0 0
11 0x1120 4384 color.black 1 color black 0 1 builtin:color true false 1 false fixed 0 0
12 0x1121 4385 color.white 1 color white 0 1 builtin:color true false 1 false fixed 0 0
13 0x1122 4386 color.red 1 color red 0 1 builtin:color true false 1 false fixed 0 0
14 0x1123 4387 color.green 1 color green 0 1 builtin:color true false 1 false fixed 0 0
15 0x1124 4388 color.blue 1 color blue 0 1 builtin:color true false 1 false fixed 0 0
16 0x1125 4389 color.yellow 1 color yellow 0 1 builtin:color true false 1 false fixed 0 0
17 0x1126 4390 color.orange 1 color orange 0 1 builtin:color true false 1 false fixed 0 0
18 0x1127 4391 color.indigo 1 color indigo 0 1 builtin:color true false 1 false fixed 0 0
19 0x1128 4392 color.gray 1 color gray 0 1 builtin:color true false 1 false fixed 0 0
20 0x1129 4393 color.cyan 1 color cyan 0 1 builtin:color true false 1 false fixed 0 0
21 0x112A 4394 color.magenta 1 color magenta 0 1 builtin:color true false 1 false fixed 0 0
22 0x112B 4395 color.transparent 1 color transparent 0 1 builtin:color true false 1 false fixed 0 0
23 0x2000 0x2100 8192 8448 input.pad input.pad.up.pressed 1 input input.pad.up pad pressed 0 1 builtin:input.pad Bool true false 1 false fixed 0 0
24 0x2001 0x2101 8193 8449 input.touch input.pad.up.released 1 input input.pad.up touch released 0 1 builtin:input.touch Bool true false 1 false fixed 0 0
25 0x2010 0x2102 8208 8450 input.pad.up input.pad.up.down 1 input.pad input.pad.up up down 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
26 0x2011 0x2103 8209 8451 input.pad.down input.pad.up.hold 1 input.pad input.pad.up down hold 1 0 1 builtin:input.pad builtin:input.button Int64 true false 1 false fixed 0 0
27 0x2012 0x2104 8210 8452 input.pad.left input.pad.down.pressed 1 input.pad input.pad.down left pressed 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
28 0x2013 0x2105 8211 8453 input.pad.right input.pad.down.released 1 input.pad input.pad.down right released 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
29 0x2014 0x2106 8212 8454 input.pad.a input.pad.down.down 1 input.pad input.pad.down a down 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
30 0x2015 0x2107 8213 8455 input.pad.b input.pad.down.hold 1 input.pad input.pad.down b hold 1 0 1 builtin:input.pad builtin:input.button Int64 true false 1 false fixed 0 0
31 0x2016 0x2108 8214 8456 input.pad.x input.pad.left.pressed 1 input.pad input.pad.left x pressed 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
32 0x2017 0x2109 8215 8457 input.pad.y input.pad.left.released 1 input.pad input.pad.left y released 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
33 0x2018 0x210A 8216 8458 input.pad.l input.pad.left.down 1 input.pad input.pad.left l down 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
34 0x2019 0x210B 8217 8459 input.pad.r input.pad.left.hold 1 input.pad input.pad.left r hold 1 0 1 builtin:input.pad builtin:input.button Int64 true false 1 false fixed 0 0
35 0x201A 0x210C 8218 8460 input.pad.start input.pad.right.pressed 1 input.pad input.pad.right start pressed 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
36 0x201B 0x210D 8219 8461 input.pad.select input.pad.right.released 1 input.pad input.pad.right select released 1 0 1 builtin:input.pad builtin:input.button Bool true false 1 false fixed 0 0
37 0x2020 0x210E 8224 8462 input.touch.button input.pad.right.down 1 input.touch input.pad.right button down 1 0 1 builtin:input.touch builtin:input.button Bool true false 1 false fixed 0 0
38 0x2021 0x210F 8225 8463 input.touch.x input.pad.right.hold 1 input.touch input.pad.right x hold 1 0 1 builtin:input.touch int Int64 true false 1 false fixed 0 0
39 0x2022 0x2110 8226 8464 input.touch.y input.pad.a.pressed 1 input.touch input.pad.a y pressed 1 0 1 builtin:input.touch int Bool true false 1 false fixed 0 0
40 0x2030 0x2111 8240 8465 input.button.pressed input.pad.a.released 1 input.button input.pad.a pressed released 1 0 1 builtin:input.button bool Bool true false 1 false fixed 0 0
41 0x2031 0x2112 8241 8466 input.button.released input.pad.a.down 1 input.button input.pad.a released down 1 0 1 builtin:input.button bool Bool true false 1 false fixed 0 0
42 0x2032 0x2113 8242 8467 input.button.down input.pad.a.hold 1 input.button input.pad.a down hold 1 0 1 builtin:input.button bool Int64 true false 1 false fixed 0 0
43 0x2033 0x2114 8243 8468 input.button.hold input.pad.b.pressed 1 input.button input.pad.b hold pressed 1 0 1 builtin:input.button int Bool true false 1 false fixed 0 0
44 0x2115 8469 input.pad.b.released 1 input.pad.b released 0 1 Bool true false 1 false fixed 0 0
45 0x2116 8470 input.pad.b.down 1 input.pad.b down 0 1 Bool true false 1 false fixed 0 0
46 0x2117 8471 input.pad.b.hold 1 input.pad.b hold 0 1 Int64 true false 1 false fixed 0 0
47 0x2118 8472 input.pad.x.pressed 1 input.pad.x pressed 0 1 Bool true false 1 false fixed 0 0
48 0x2119 8473 input.pad.x.released 1 input.pad.x released 0 1 Bool true false 1 false fixed 0 0
49 0x211A 8474 input.pad.x.down 1 input.pad.x down 0 1 Bool true false 1 false fixed 0 0
50 0x211B 8475 input.pad.x.hold 1 input.pad.x hold 0 1 Int64 true false 1 false fixed 0 0
51 0x211C 8476 input.pad.y.pressed 1 input.pad.y pressed 0 1 Bool true false 1 false fixed 0 0
52 0x211D 8477 input.pad.y.released 1 input.pad.y released 0 1 Bool true false 1 false fixed 0 0
53 0x211E 8478 input.pad.y.down 1 input.pad.y down 0 1 Bool true false 1 false fixed 0 0
54 0x211F 8479 input.pad.y.hold 1 input.pad.y hold 0 1 Int64 true false 1 false fixed 0 0
55 0x2120 8480 input.pad.l.pressed 1 input.pad.l pressed 0 1 Bool true false 1 false fixed 0 0
56 0x2121 8481 input.pad.l.released 1 input.pad.l released 0 1 Bool true false 1 false fixed 0 0
57 0x2122 8482 input.pad.l.down 1 input.pad.l down 0 1 Bool true false 1 false fixed 0 0
58 0x2123 8483 input.pad.l.hold 1 input.pad.l hold 0 1 Int64 true false 1 false fixed 0 0
59 0x2124 8484 input.pad.r.pressed 1 input.pad.r pressed 0 1 Bool true false 1 false fixed 0 0
60 0x2125 8485 input.pad.r.released 1 input.pad.r released 0 1 Bool true false 1 false fixed 0 0
61 0x2126 8486 input.pad.r.down 1 input.pad.r down 0 1 Bool true false 1 false fixed 0 0
62 0x2127 8487 input.pad.r.hold 1 input.pad.r hold 0 1 Int64 true false 1 false fixed 0 0
63 0x2128 8488 input.pad.start.pressed 1 input.pad.start pressed 0 1 Bool true false 1 false fixed 0 0
64 0x2129 8489 input.pad.start.released 1 input.pad.start released 0 1 Bool true false 1 false fixed 0 0
65 0x212A 8490 input.pad.start.down 1 input.pad.start down 0 1 Bool true false 1 false fixed 0 0
66 0x212B 8491 input.pad.start.hold 1 input.pad.start hold 0 1 Int64 true false 1 false fixed 0 0
67 0x212C 8492 input.pad.select.pressed 1 input.pad.select pressed 0 1 Bool true false 1 false fixed 0 0
68 0x212D 8493 input.pad.select.released 1 input.pad.select released 0 1 Bool true false 1 false fixed 0 0
69 0x212E 8494 input.pad.select.down 1 input.pad.select down 0 1 Bool true false 1 false fixed 0 0
70 0x212F 8495 input.pad.select.hold 1 input.pad.select hold 0 1 Int64 true false 1 false fixed 0 0
71 0x2130 8496 input.touch.button.pressed 1 input.touch.button pressed 0 1 Bool true false 1 false fixed 0 0
72 0x2131 8497 input.touch.button.released 1 input.touch.button released 0 1 Bool true false 1 false fixed 0 0
73 0x2132 8498 input.touch.button.down 1 input.touch.button down 0 1 Bool true false 1 false fixed 0 0
74 0x2133 8499 input.touch.button.hold 1 input.touch.button hold 0 1 Int64 true false 1 false fixed 0 0
75 0x2134 8500 input.touch.x 1 input.touch x 0 1 Int64 true false 1 false fixed 0 0
76 0x2135 8501 input.touch.y 1 input.touch y 0 1 Int64 true false 1 false fixed 0 0
77 0x3000 12288 math.i32.min 1 math.i32 min 2 1 Int32|Int32 Int32 true false a|b 2 false fixed 0 0
78 0x3001 12289 math.i32.max 1 math.i32 max 2 1 Int32|Int32 Int32 true false a|b 2 false fixed 0 0
79 0x3002 12290 math.i32.clamp 1 math.i32 clamp 3 1 Int32|Int32|Int32 Int32 true false value|min|max 4 false fixed 0 0
80 0x3003 12291 math.i32.abs 1 math.i32 abs 1 1 Int32 Int32 true false value 2 false fixed 0 0
81 0x3004 12292 math.i64.min 1 math.i64 min 2 1 Int64|Int64 Int64 true false a|b 2 false fixed 0 0
82 0x3005 12293 math.i64.max 1 math.i64 max 2 1 Int64|Int64 Int64 true false a|b 2 false fixed 0 0
83 0x3006 12294 math.i64.clamp 1 math.i64 clamp 3 1 Int64|Int64|Int64 Int64 true false value|min|max 4 false fixed 0 0
84 0x3007 12295 math.i64.abs 1 math.i64 abs 1 1 Int64 Int64 true false value 2 false fixed 0 0
85 0x3008 12296 mathf.min 1 mathf min 2 1 Float|Float Float true false a|b 2 false fixed 0 0
86 0x3009 12297 mathf.max 1 mathf max 2 1 Float|Float Float true false a|b 2 false fixed 0 0
87 0x300A 12298 mathf.clamp 1 mathf clamp 3 1 Float|Float|Float Float true false value|min|max 4 false fixed 0 0
88 0x300B 12299 mathf.abs 1 mathf abs 1 1 Float Float true false value 2 false fixed 0 0
89 0x300C 12300 mathf.floor 1 mathf floor 1 1 Float Float true false value 4 false fixed 0 0
90 0x300D 12301 mathf.ceil 1 mathf ceil 1 1 Float Float true false value 4 false fixed 0 0
91 0x300E 12302 mathf.trunc 1 mathf trunc 1 1 Float Float true false value 4 false fixed 0 0
92 0x300F 12303 mathf.round 1 mathf round 1 1 Float Float true false value 4 false fixed 0 0
93 0x3010 12304 mathf.sqrt 1 mathf sqrt 1 1 Float Float true false value 16 false fixed 0 0
94 0x3011 12305 mathf.sin 1 mathf sin 1 1 Float Float true false angle 32 false fixed 0 0
95 0x3012 12306 mathf.cos 1 mathf cos 1 1 Float Float true false angle 32 false fixed 0 0
96 0x3013 12307 mathf.atan2 1 mathf atan2 2 1 Float|Float Float true false y|x 48 false fixed 0 0
97 0x3014 12308 math.i32.to_i64 1 math.i32 to_i64 1 1 Int32 Int64 true false value 2 false fixed 0 0
98 0x3015 12309 math.i64.to_i32 1 math.i64 to_i32 1 1 Int64 Int32 true false value 2 false fixed 0 0
99 0x3016 12310 math.i32.to_float 1 math.i32 to_float 1 1 Int32 Float true false value 2 false fixed 0 0
100 0x3017 12311 math.i64.to_float 1 math.i64 to_float 1 1 Int64 Float true false value 2 false fixed 0 0
101 0x3018 12312 mathf.to_i32 1 mathf to_i32 1 1 Float Int32 true false value 2 false fixed 0 0
102 0x3019 12313 mathf.to_i64 1 mathf to_i64 1 1 Float Int64 true false value 2 false fixed 0 0
103 0x4000 16384 random.new 1 random new 1 1 Int64 builtin:Random true true seed 32 true fixed 0 0
104 0x4001 16385 random.next 1 random next 1 1 builtin:Random Int64 true false rng 8 true fixed 0 0
105 0x4002 16386 random.nextf 1 random nextf 1 1 builtin:Random Float true false rng 12 true fixed 0 0
106 0x4003 16387 random.range 1 random range 3 1 builtin:Random|Int64|Int64 Int64 true false rng|min|max 4 true random_rejection_v1 8 64
+24 -1
View File
@@ -10,6 +10,7 @@ Canonical runtime sources:
- `../runtime/docs/vm-arch/ARCHITECTURE.md` - `../runtime/docs/vm-arch/ARCHITECTURE.md`
- `../runtime/docs/vm-arch/ISA_CORE.md` - `../runtime/docs/vm-arch/ISA_CORE.md`
- `../runtime/docs/vm-arch/INTRINSICS.csv` - `../runtime/docs/vm-arch/INTRINSICS.csv`
- `../runtime/docs/vm-arch/BUILTIN_CONSTANTS.csv`
When these mirrors are retained, an integration change that updates a canonical When these mirrors are retained, an integration change that updates a canonical
runtime source MUST update the corresponding Studio mirror in the same logical runtime source MUST update the corresponding Studio mirror in the same logical
@@ -19,9 +20,10 @@ change. Verify synchronization from the Studio repository root with:
diff -u docs/vm-arch/ARCHITECTURE.md ../runtime/docs/vm-arch/ARCHITECTURE.md diff -u docs/vm-arch/ARCHITECTURE.md ../runtime/docs/vm-arch/ARCHITECTURE.md
diff -u docs/vm-arch/ISA_CORE.md ../runtime/docs/vm-arch/ISA_CORE.md diff -u docs/vm-arch/ISA_CORE.md ../runtime/docs/vm-arch/ISA_CORE.md
diff -u docs/vm-arch/INTRINSICS.csv ../runtime/docs/vm-arch/INTRINSICS.csv diff -u docs/vm-arch/INTRINSICS.csv ../runtime/docs/vm-arch/INTRINSICS.csv
diff -u docs/vm-arch/BUILTIN_CONSTANTS.csv ../runtime/docs/vm-arch/BUILTIN_CONSTANTS.csv
``` ```
All three commands MUST exit successfully with no output before a change claims All four commands MUST exit successfully with no output before a change claims
that the mirrors are synchronized. If the runtime repository is not available that the mirrors are synchronized. If the runtime repository is not available
in the same checkout, synchronization evidence must be produced against the in the same checkout, synchronization evidence must be produced against the
canonical runtime revision before merging. canonical runtime revision before merging.
@@ -30,3 +32,24 @@ Compiler-owned transformation contracts remain under `docs/specs/compiler`.
Those specifications define `IRBackend -> IRVM -> PBX` emission, but they MUST Those specifications define `IRBackend -> IRVM -> PBX` emission, but they MUST
conform to the runtime-owned PBX and ISA contracts and MUST NOT redefine runtime conform to the runtime-owned PBX and ISA contracts and MUST NOT redefine runtime
execution semantics. execution semantics.
## Catalog provenance
`runtime-catalog.properties` identifies the selected provider revision and hashes
of both CSVs. The compiler and PBS SDK package these artifacts with their own
resource namespaces. Catalog synchronization alone does not claim the other
architecture mirrors are synchronized or that all PBS facades are implemented.
Run the explicit source/exporter verification from the Studio root:
```sh
python3 tools/runtime-catalog/verify.py --runtime ../runtime
```
This command requires a clean checkout of the recorded provider revision, compares
committed bytes and hashes, and runs its real catalog exporter parity test with
build output in a temporary directory. Missing or different evidence sources fail
explicitly. Ordinary builds and local catalog tests never invoke this command.
The manual port and consumer requirements are defined in
[Runtime catalog support](../compiler/general/specs/runtime-catalog-support.md).
+3
View File
@@ -0,0 +1,3 @@
runtime.revision=f7d7c167531bb662a1af9d73fc326bb476bf8aa7
INTRINSICS.csv.sha256=0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa
BUILTIN_CONSTANTS.csv.sha256=e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039
+11 -6
View File
@@ -27,17 +27,22 @@ pipeline {
--no-daemon --no-daemon
""" """
} }
junit testResults: '**/build/test-results/test/TEST-*.xml'
}
withChecks(name: 'JaCoCo Coverage', includeStage: false) {
recordCoverage(tools: [[parser: 'JACOCO', pattern: "build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml"]], recordCoverage(tools: [[parser: 'JACOCO', pattern: "build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml"]],
id: 'jacoco', id: 'jacoco',
name: 'JaCoCo Coverage', name: 'JaCoCo Coverage',
checksName: 'JaCoCo Coverage',
sourceDirectories: [[path: 'glob:**/src/main/java']],
sourceCodeEncoding: 'UTF-8',
sourceCodeRetention: 'EVERY_BUILD', sourceCodeRetention: 'EVERY_BUILD',
qualityGates: [ qualityGates: [
[threshold: 50.0, metric: 'CLASS', baseline: 'PROJECT', unstable: true], [threshold: 50.0, metric: 'CLASS', baseline: 'PROJECT', criticality: 'UNSTABLE'],
[threshold: 50.0, metric: 'METHOD', baseline: 'PROJECT', unstable: true], [threshold: 50.0, metric: 'METHOD', baseline: 'PROJECT', criticality: 'UNSTABLE'],
[threshold: 50.0, metric: 'LINE', baseline: 'PROJECT', unstable: true], [threshold: 50.0, metric: 'LINE', baseline: 'PROJECT', criticality: 'UNSTABLE'],
[threshold: 50.0, metric: 'INSTRUCTION', baseline: 'PROJECT', unstable: true], [threshold: 50.0, metric: 'INSTRUCTION', baseline: 'PROJECT', criticality: 'UNSTABLE'],
[threshold: 40.0, metric: 'BRANCH', baseline: 'PROJECT', unstable: true]]) [threshold: 40.0, metric: 'BRANCH', baseline: 'PROJECT', criticality: 'UNSTABLE']])
junit testResults: '**/build/test-results/test/TEST-*.xml'
} }
} }
} // Test } // Test
+1
View File
@@ -12,6 +12,7 @@ spring-boot = "3.5.16"
spring-modulith = "1.4.13" spring-modulith = "1.4.13"
[libraries] [libraries]
tomlj = { group = "org.tomlj", name = "tomlj", version = "1.1.1" }
javafx-controls = { group = "org.openjfx", name = "javafx-controls", version.ref = "javafx" } javafx-controls = { group = "org.openjfx", name = "javafx-controls", version.ref = "javafx" }
javafx-fxml = { group = "org.openjfx", name = "javafx-fxml", version.ref = "javafx" } javafx-fxml = { group = "org.openjfx", name = "javafx-fxml", version.ref = "javafx" }
richtextfx = { group = "org.fxmisc.richtext", name = "richtextfx", version.ref = "richtextfx" } richtextfx = { group = "org.fxmisc.richtext", name = "richtextfx", version.ref = "richtextfx" }
+97
View File
@@ -4,18 +4,21 @@ plugins {
} }
dependencies { dependencies {
implementation(libs.tomlj)
implementation(project(":prometeu-infra")) implementation(project(":prometeu-infra"))
implementation(project(":prometeu-lsp:prometeu-lsp-api")) implementation(project(":prometeu-lsp:prometeu-lsp-api"))
implementation(project(":prometeu-lsp:prometeu-lsp-v1")) implementation(project(":prometeu-lsp:prometeu-lsp-v1"))
implementation(project(":prometeu-compiler:prometeu-compiler-core")) implementation(project(":prometeu-compiler:prometeu-compiler-core"))
implementation(project(":prometeu-compiler:prometeu-build-pipeline")) implementation(project(":prometeu-compiler:prometeu-build-pipeline"))
implementation(project(":prometeu-compiler:prometeu-frontend-registry")) 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-api"))
implementation(project(":prometeu-packer:prometeu-packer-v1")) implementation(project(":prometeu-packer:prometeu-packer-v1"))
implementation(project(":prometeu-studio-api")) implementation(project(":prometeu-studio-api"))
implementation(project(":prometeu-studio-core")) implementation(project(":prometeu-studio-core"))
implementation(project(":prometeu-studio-ui-javafx")) implementation(project(":prometeu-studio-ui-javafx"))
implementation(libs.spring.boot) implementation(libs.spring.boot)
implementation(libs.lsp4j)
implementation(libs.javafx.controls) implementation(libs.javafx.controls)
implementation(libs.javafx.fxml) implementation(libs.javafx.fxml)
} }
@@ -24,7 +27,101 @@ application {
mainClass = "p.studio.app.StudioLauncher" mainClass = "p.studio.app.StudioLauncher"
} }
val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) }
val studioRuntime = layout.buildDirectory.dir("studio-runtime")
val assembleStudioRuntime by tasks.registering(Exec::class) {
val jdk = studioJava.get().metadata.installationPath.asFile
inputs.property("jdk", jdk.absolutePath)
outputs.dir(studioRuntime)
doFirst { delete(studioRuntime) }
// jlink license files can be read-only; Gradle Sync must be able to refresh the installed image.
doLast {
studioRuntime.get().asFile.walkTopDown().filter { it.isFile }.forEach {
check(it.setWritable(true, true)) { "Cannot normalize staged runtime permissions" }
}
}
commandLine(jdk.resolve("bin/jlink"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files",
"--no-man-pages", "--output", studioRuntime.get().asFile)
}
distributions {
main { contents { from(assembleStudioRuntime) { into("runtime") } } }
}
tasks.register<JavaExec>("stageStudioInstallation") {
group = "application"
description = "Stages and validates the bundled Studio/Java installation; no project launcher is created."
dependsOn(tasks.named("installDist"))
classpath = sourceSets["main"].runtimeClasspath
mainClass = "p.studio.app.install.ManagedStudioInstallation"
args(layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath,
providers.gradleProperty("studioInstallationRoot").getOrElse(
"${System.getProperty("user.home")}/Library/Application Support/Prometeu/Studio"))
}
javafx { javafx {
version = libs.versions.javafx.get() version = libs.versions.javafx.get()
modules("javafx.controls", "javafx.fxml") modules("javafx.controls", "javafx.fxml")
} }
// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests.
tasks.named<Test>("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class") }
tasks.register<Test>("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")
}
tasks.register<Test>("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)
}
tasks.register<Test>("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")
include("**/HeadlessTaskIntegrationTest.class")
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
}
tasks.register<Test>("headlessMcpDesktopTest") {
group = "verification"
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()
include("**/HeadlessMcpDesktopTest.class")
systemProperty("java.awt.headless", "false")
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
}
// Subprocess tests exercise the actual Studio main and OS ownership boundaries.
tasks.withType<Test>().configureEach {
systemProperty("studio.test.classpath", sourceSets["test"].runtimeClasspath.asPath)
}
tasks.named<Test>("test") { exclude("**/InstalledConnectorTest.class") }
tasks.register<Test>("installedConnectorTest") {
group = "verification"
description = "Validates installed Java, stable updates, project preparation and JavaFX startup (requires a display)."
dependsOn(tasks.named("installDist"))
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform()
include("**/InstalledConnectorTest.class")
systemProperty("studio.test.distribution", layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath)
}
@@ -101,18 +101,18 @@ public class StudioApplicationConfiguration {
} }
@Bean @Bean
AssetCatalog assetCatalog(PackerWorkspaceService packer) { AssetCatalog assetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) {
return new PackerAssetCatalog(packer); return new PackerAssetCatalog(packer, access);
} }
@Bean @Bean
AssetCommands assetCommands(PackerWorkspaceService packer) { AssetCommands assetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) {
return new PackerAssetCommands(packer); return new PackerAssetCommands(packer, access);
} }
@Bean @Bean
AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations) { AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new PackerAssetPacking(packer, operations); return new PackerAssetPacking(packer, operations, access);
} }
@Bean @Bean
@@ -126,8 +126,8 @@ public class StudioApplicationConfiguration {
} }
@Bean @Bean
AssetWorkspaceStorage assetWorkspaceStorage() { AssetWorkspaceStorage assetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) {
return new FileSystemAssetWorkspaceStorage(); return new FileSystemAssetWorkspaceStorage(access);
} }
@Bean @Bean
@@ -146,18 +146,18 @@ public class StudioApplicationConfiguration {
} }
@Bean @Bean
AssetMetadataService assetMetadataService(ObjectMapper mapper) { AssetMetadataService assetMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
return new AssetStudioMetadataService(mapper); return new AssetStudioMetadataService(mapper, access);
} }
@Bean @Bean
SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper) { SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
return new SceneBankWorkflowService(assetCatalog, mapper); return new SceneBankWorkflowService(assetCatalog, mapper, access);
} }
@Bean @Bean
TiledAssetService tiledAssetService(AssetMetadataService metadataService) { TiledAssetService tiledAssetService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) {
return new TiledAssetGenerationService(metadataService); return new TiledAssetGenerationService(metadataService, access);
} }
@Bean @Bean
@@ -176,9 +176,9 @@ public class StudioApplicationConfiguration {
} }
@Bean @Bean
Shipper shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, StudioShipperService shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper,
OperationExecutor operations) { OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new StudioShipperService(compiler, packer, mapper, operations); return new StudioShipperService(compiler, packer, mapper, operations, access);
} }
@Bean(destroyMethod = "shutdown") @Bean(destroyMethod = "shutdown")
@@ -198,8 +198,8 @@ public class StudioApplicationConfiguration {
@Bean @Bean
ExecutionControllerFactory executionControllerFactory(Shipper shipper, RuntimeGateway runtime, ExecutionControllerFactory executionControllerFactory(Shipper shipper, RuntimeGateway runtime,
OperationExecutor operations) { OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new DefaultExecutionControllerFactory(shipper, runtime, operations); return new DefaultExecutionControllerFactory(shipper, runtime, operations, access);
} }
@Bean @Bean
@@ -223,14 +223,23 @@ public class StudioApplicationConfiguration {
} }
@Bean @Bean
ProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore, p.studio.core.project.ProjectAccessRegistry projectAccessRegistry() {
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) { return new p.studio.core.project.ProjectAccessRegistry();
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp); }
@Bean(destroyMethod = "close")
DefaultProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore,
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations,
p.studio.api.automation.AutomationConnectionLifecycle connections,
p.studio.api.automation.AgentIntegrationPreparation preparation) {
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations, connections, preparation);
} }
@Bean @Bean
ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) { ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore,
return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore); p.studio.api.automation.AgentIntegrationPreparation preparation) {
return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore, preparation);
} }
@Bean @Bean
@@ -275,13 +284,78 @@ public class StudioApplicationConfiguration {
TiledAssetService tiledAssetService, TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow, SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore, WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore) { ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) {
return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory, return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper, executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore, tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore); activityHistoryStore, connectionGuide);
}
@Bean
p.studio.app.mcp.McpToolCatalog mcpToolCatalog(ObjectMapper mapper) {
return new p.studio.app.mcp.McpToolCatalog(mapper);
}
@Bean
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.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.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,
java.util.Optional<p.studio.core.runtime.HeadlessGateway> 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,
p.studio.api.automation.TaskTools tasks, java.util.Optional<p.studio.core.runtime.HeadlessGateway> 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);
}
@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);
}
@Bean
p.studio.api.automation.AutomationConnectionLifecycle connectionLifecycle(p.studio.app.mcp.LocalMcpServer server, ObjectMapper mapper) {
return new p.studio.app.mcp.ProjectConnectionPublisher(server, mapper);
}
@Bean
p.studio.api.automation.AgentIntegrationPreparation agentPreparation(ObjectMapper mapper) {
return new p.studio.app.mcp.StudioAgentPreparation(p.studio.app.install.ManagedStudioInstallation.defaultRoot(), mapper);
}
@Bean
p.studio.api.automation.AgentConnectionGuide connectionGuide(p.studio.app.mcp.LocalMcpServer server,
p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper,
p.studio.api.automation.AgentIntegrationPreparation preparation) {
return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper, preparation);
} }
private static Path resolveDefaultProjectsRoot() { private static Path resolveDefaultProjectsRoot() {
@@ -7,6 +7,11 @@ public final class StudioLauncher {
} }
public static void main(String[] args) { public static void main(String[] args) {
if (args.length > 0 && "mcp".equals(args[0])) {
try { p.studio.app.mcp.stdio.StudioMcpStdio.main(args); }
catch (Exception failure) { System.err.println("Studio MCP could not start. Check --project, the manifest and installation."); System.exit(1); }
return;
}
Application.launch(App.class, args); Application.launch(App.class, args);
} }
} }
@@ -56,6 +56,7 @@ public final class StudioUiFactory {
private final SceneBankWorkflow sceneBankWorkflow; private final SceneBankWorkflow sceneBankWorkflow;
private final WindowStateStore windowStateStore; private final WindowStateStore windowStateStore;
private final ProjectActivityHistoryStore activityHistoryStore; private final ProjectActivityHistoryStore activityHistoryStore;
private final p.studio.api.automation.AgentConnectionGuide connectionGuide;
public StudioUiFactory( public StudioUiFactory(
ProjectCatalog projectCatalog, ProjectCatalog projectCatalog,
@@ -82,7 +83,8 @@ public final class StudioUiFactory {
TiledAssetService tiledAssetService, TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow, SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore, WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore) { ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) {
this.connectionGuide = Objects.requireNonNull(connectionGuide);
this.projectCatalog = Objects.requireNonNull(projectCatalog, "projectCatalog"); this.projectCatalog = Objects.requireNonNull(projectCatalog, "projectCatalog");
this.knownProjects = Objects.requireNonNull(knownProjects, "knownProjects"); this.knownProjects = Objects.requireNonNull(knownProjects, "knownProjects");
this.languageCatalog = Objects.requireNonNull(languageCatalog, "languageCatalog"); this.languageCatalog = Objects.requireNonNull(languageCatalog, "languageCatalog");
@@ -116,6 +118,6 @@ public final class StudioUiFactory {
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore, tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore); activityHistoryStore, connectionGuide);
} }
} }
@@ -0,0 +1,287 @@
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 record OwnedReference(String owner, p.studio.compiler.services.FrontendReferenceProvider.Reference reference) {}
private record Discovery(Context context, Map<String, OwnedReference> references) {}
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) {
return discover(openProjectRoot).context();
}
private Discovery discover(Path openProjectRoot) {
Path root = openProjects.requireOpenRoot(openProjectRoot);
var limitations = new ArrayList<String>();
var discovered = new LinkedHashMap<Path, ProjectReference>();
var dependencies = new LinkedHashMap<Path, List<Path>>();
var readOnly = new LinkedHashSet<Path>();
var unresolved = new ArrayList<Library>();
var pending = new ArrayDeque<Path>();
var visited = new HashSet<Path>();
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<Path>();
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<Path>();
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<Library>();
var byLanguage = new LinkedHashMap<String, List<ProjectReference>>();
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 references = new LinkedHashMap<String, OwnedReference>();
discovered.values().forEach(project -> collectReferences(project, references, limitations));
var languages = new ArrayList<Language>();
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,
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()) {
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("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 -> {
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<ProjectReference> projects, boolean primary,
boolean graphBuildable, List<String> limitations, List<String> 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();
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)), referenceIds);
}
var spec = provider.get().specification();
var roots = new LinkedHashSet<Path>();
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<Capability>();
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, referenceIds);
}
private void collectReferences(ProjectReference project, Map<String, OwnedReference> references, List<String> 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<String, OwnedReference>();
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<Capability> capabilities, List<String> 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("semanticTokens", 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);
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);
}
}
@@ -0,0 +1,55 @@
package p.studio.app.install;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
/** One versioned application installation; client entries always refer to current. */
public final class ManagedStudioInstallation {
public static final class MissingInstallation extends IOException {
public MissingInstallation() {
super("Studio installation is missing. In the Studio checkout, run ./gradlew :prometeu-app:stageStudioInstallation, then prepare the assistant again. If using an isolated installation, set -Dstudio.installationRoot to that installation in the desktop VM options.");
}
}
private ManagedStudioInstallation() { }
public static Path defaultRoot() {
return Path.of(System.getProperty("studio.installationRoot", Path.of(System.getProperty("user.home"),
"Library", "Application Support", "Prometeu", "Studio").toString())).toAbsolutePath();
}
public static void ensureAvailable(Path base) throws Exception {
if (Files.isExecutable(base.resolve("current/runtime/bin/java")) && Files.isDirectory(base.resolve("current/lib"))) return;
Path location = Path.of(ManagedStudioInstallation.class.getProtectionDomain().getCodeSource().getLocation().toURI());
if (!Files.isRegularFile(location) || !Files.isDirectory(location.getParent().getParent().resolve("runtime")))
throw new MissingInstallation();
install(location.getParent().getParent(), base);
}
public static synchronized Path install(Path source, Path base) throws Exception {
source = source.toRealPath(); Files.createDirectories(base.resolve("versions"));
Path version = base.resolve("versions").resolve(UUID.randomUUID().toString());
Files.createDirectory(version);
for (String part : List.of("lib", "runtime")) {
if (!Files.isDirectory(source.resolve(part))) throw new IOException("Incomplete Studio distribution");
try (var paths = Files.walk(source.resolve(part))) {
for (Path from : paths.toList()) {
Path to = version.resolve(source.relativize(from));
if (Files.isDirectory(from)) Files.createDirectories(to);
else Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES);
}
}
}
var process = new ProcessBuilder(version.resolve("runtime/bin/java").toString(), "-cp", version.resolve("lib/*").toString(),
"p.studio.app.install.StudioInstallationProbe").redirectError(ProcessBuilder.Redirect.DISCARD).redirectOutput(ProcessBuilder.Redirect.DISCARD).start();
if (!process.waitFor(30, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Installation validation timed out"); }
if (process.exitValue() != 0) throw new IOException("Installation validation failed");
Path link = base.resolve(".current-" + UUID.randomUUID());
try { Files.createSymbolicLink(link, base.toAbsolutePath().relativize(version.toAbsolutePath()));
Files.move(link, base.resolve("current"), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} finally { Files.deleteIfExists(link); }
return version;
}
public static void main(String[] args) throws Exception {
if (args.length != 2) throw new IllegalArgumentException("distribution and installation root required");
install(Path.of(args[0]), Path.of(args[1]));
}
}
@@ -0,0 +1,12 @@
package p.studio.app.install;
/** Packaging health check; it never starts the GUI or opens projects. */
public final class StudioInstallationProbe {
public static void main(String[] args) throws Exception {
var catalog = new p.studio.app.mcp.McpToolCatalog(new com.fasterxml.jackson.databind.ObjectMapper());
if (catalog.names().isEmpty()) throw new IllegalStateException("Missing catalog");
for (String type : java.util.List.of("javafx.application.Application", "javafx.fxml.FXMLLoader",
"p.studio.app.App", "java.net.http.HttpClient", "com.sun.net.httpserver.HttpServer", "org.tomlj.Toml"))
Class.forName(type, false, StudioInstallationProbe.class.getClassLoader());
}
}
@@ -0,0 +1,354 @@
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 p.studio.lsp.services.protocol.ExternalSourceLanguageServer;
import org.eclipse.lsp4j.jsonrpc.Launcher;
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<TaskIdentity, Map<String, CallHierarchyItem>> items = new ConcurrentHashMap<>();
private static final Set<String> OPERATIONS = Set.of("readExternalSource", "diagnostics", "completion", "hover", "signatureHelp", "definition",
"references", "documentSymbols", "workspaceSymbols", "prepareRename", "rename", "codeActions", "formatting",
"documentLinks", "foldingRanges", "selectionRanges", "prepareCallHierarchy", "incomingCalls", "outgoingCalls", "semanticTokens");
private static final Set<String> 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;
}
private record ExternalTask(String consumer, p.studio.lsp.messages.LspServerEndpoint endpoint,
p.studio.lsp.messages.LspProjectContext binding, Set<String> uris) {}
private final Map<TaskIdentity, ExternalTask> externalTasks = new ConcurrentHashMap<>();
@Override public void endTask(TaskIdentity task) {
items.remove(task);
final var state = externalTasks.remove(task);
if (state == null) return;
final var workers = Executors.newCachedThreadPool();
try (var socket = new Socket()) {
socket.connect(new InetSocketAddress(state.endpoint().host(), state.endpoint().port()), 2000);
final var client = new QuietClient();
final var launcher = new Launcher.Builder<ExternalSourceLanguageServer>().setLocalService(client)
.setRemoteInterface(ExternalSourceLanguageServer.class).setInput(socket.getInputStream())
.setOutput(socket.getOutputStream()).setExecutorService(workers).create();
final var listening = launcher.startListening();
try {
final var server = launcher.getRemoteProxy();
final var init = new InitializeParams();
init.setRootUri(state.binding().projectRoot().toUri().toString());
init.setCapabilities(new ClientCapabilities());
init.getCapabilities().setExperimental(Map.of("prometeuExternalSources", true));
init.setInitializationOptions(Map.of("prometeuExternalConsumerId", state.consumer()));
server.initialize(init).get(2, TimeUnit.SECONDS);
server.releaseExternalSource(new ExternalSourceLanguageServer.Request(state.consumer(), null)).get(2, TimeUnit.SECONDS);
} finally { listening.cancel(true); }
} catch (Exception failure) {
// A closed project host has already released its registry. Other cleanup
// failures are surfaced instead of silently reporting a successful task end.
if (lifecycle.endpoint(state.binding()).isPresent())
throw new IllegalStateException("Could not release task external sources", failure);
} finally { workers.shutdownNow(); }
}
private static class QuietClient implements LanguageClient {
public void telemetryEvent(Object event) {}
public void publishDiagnostics(PublishDiagnosticsParams event) {}
public void showMessage(MessageParams message) {}
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams request) { return CompletableFuture.completedFuture(null); }
public void logMessage(MessageParams message) {}
}
@Override public Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> 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");
}
final boolean external = uri != null && uri.startsWith("prometeu-source:");
if (external) {
final var state = externalTasks.get(task);
if (state == null || !state.uris().contains(uri)) throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Unknown task-owned external source");
if (EDITS.contains(operation)) throw failure(AutomationFailure.Code.READ_ONLY_SCOPE, "External sources are read-only");
if (!Set.of("readExternalSource", "hover", "definition").contains(operation))
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "Operation is unavailable for external documents");
} else if (operation.equals("readExternalSource")) throw new IllegalArgumentException("An external source URI is required");
Path document = uri == null || external ? 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<List<Diagnostic>>();
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<MessageActionItem> showMessageRequest(ShowMessageRequestParams request) { return CompletableFuture.completedFuture(null); }
public void logMessage(MessageParams message) {}
@Override public CompletableFuture<ApplyWorkspaceEditResponse> applyEdit(ApplyWorkspaceEditParams edit) {
return CompletableFuture.completedFuture(new ApplyWorkspaceEditResponse(false));
}
};
var launcher = new Launcher.Builder<ExternalSourceLanguageServer>().setLocalService(client)
.setRemoteInterface(ExternalSourceLanguageServer.class).setInput(socket.getInputStream())
.setOutput(socket.getOutputStream()).setExecutorService(workers).create();
var listening = launcher.startListening();
final var server = launcher.getRemoteProxy();
final var acquired = new HashSet<String>();
boolean succeeded = false;
try {
var initialize = new InitializeParams();
initialize.setRootUri(binding.projectRoot().toUri().toString());
initialize.setCapabilities(new ClientCapabilities());
initialize.getCapabilities().setExperimental(Map.of("prometeuExternalSources", true));
final var previous = externalTasks.get(task);
initialize.setInitializationOptions(previous == null
? Map.of("prometeuExternalPersistentConsumer", true)
: Map.of("prometeuExternalConsumerId", previous.consumer(), "prometeuExternalPersistentConsumer", true));
var capabilities = await(server.initialize(initialize), deadline).getCapabilities();
final var experimental = gson.toJsonTree(capabilities.getExperimental());
if (experimental.isJsonObject() && experimental.getAsJsonObject().has("prometeuExternalConsumerId")) {
final String consumer = experimental.getAsJsonObject().get("prometeuExternalConsumerId").getAsString();
externalTasks.putIfAbsent(task, new ExternalTask(consumer, endpoint, binding, ConcurrentHashMap.newKeySet()));
}
server.initialized(new InitializedParams());
requireCapability(operation, capabilities);
List<Diagnostic> 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);
}
if (external) {
final var request = new ExternalSourceLanguageServer.Request(externalTasks.get(task).consumer(), uri);
source = await(server.revalidateExternalSource(request), deadline).text();
if (source.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 4 * 1024 * 1024)
throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "External source exceeds 4 MiB");
}
var text = server.getTextDocumentService();
var id = uri == null ? null : new TextDocumentIdentifier(uri);
Object result = switch (operation) {
case "readExternalSource" -> await(server.readExternalSource(
new ExternalSourceLanguageServer.Request(externalTasks.get(task).consumer(), uri)), deadline);
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<Position>();
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);
if (operation.equals("definition") && externalTasks.containsKey(task)) {
final var returned = new HashSet<String>();
rememberExternalUris(returned, wire);
acquired.addAll(returned);
acquired.removeAll(externalTasks.get(task).uris());
for (String externalUri : returned) {
await(server.retainExternalSource(new ExternalSourceLanguageServer.Request(
externalTasks.get(task).consumer(), externalUri)), deadline);
externalTasks.get(task).uris().add(externalUri);
}
}
var limitations = new ArrayList<String>();
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<String, Object>();
output.put("operation", operation); output.put("result", mapper.convertValue(wire, Object.class));
output.put("limitations", limitations);
succeeded = true;
return Collections.unmodifiableMap(output);
} finally {
if (!succeeded && !acquired.isEmpty() && externalTasks.containsKey(task)) {
final var state = externalTasks.get(task);
final boolean interrupted = Thread.interrupted();
try {
for (String acquiredUri : acquired) {
state.uris().remove(acquiredUri);
server.releaseExternalSource(new ExternalSourceLanguageServer.Request(state.consumer(), acquiredUri))
.get(500, TimeUnit.MILLISECONDS);
}
} finally { if (interrupted) Thread.currentThread().interrupt(); }
}
listening.cancel(true);
}
} finally { workers.shutdownNow(); }
}
private void rememberExternalUris(Set<String> uris, com.fasterxml.jackson.databind.JsonNode node) {
if (node.isObject() && node.path("uri").asText().startsWith("prometeu-source:")) uris.add(node.path("uri").asText());
if (node.isContainerNode()) node.forEach(child -> rememberExternalUris(uris, child));
}
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) {
if (operation.equals("readExternalSource")) {
final var raw = new com.google.gson.Gson().toJsonTree(caps.getExperimental());
if (!raw.isJsonObject() || !raw.getAsJsonObject().has("prometeuExternalSources"))
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise external sources");
return;
}
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> T await(CompletableFuture<T> 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 == -32010) throw failure(AutomationFailure.Code.READ_ONLY_SCOPE, response.getResponseError().getMessage());
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); }
}
@@ -10,6 +10,7 @@ import java.util.Objects;
public final class LspLifecycleAdapter implements LspLifecyclePort { public final class LspLifecycleAdapter implements LspLifecyclePort {
private final LspServerLifecycle lifecycle; private final LspServerLifecycle lifecycle;
private final java.util.Map<java.nio.file.Path, LspProjectContext> bindings = new java.util.concurrent.ConcurrentHashMap<>();
public LspLifecycleAdapter(LspServerLifecycle lifecycle) { public LspLifecycleAdapter(LspServerLifecycle lifecycle) {
this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle"); this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle");
@@ -17,19 +18,26 @@ public final class LspLifecycleAdapter implements LspLifecyclePort {
@Override @Override
public void boot(ProjectReference project) { 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 @Override
public void shutdown(ProjectReference project) { 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 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( return new LspProjectContext(
safeProject.rootPath().toAbsolutePath().normalize().toString(), root.toString(),
safeProject.languageId(), safeProject.languageId(),
safeProject.rootPath()); root);
} }
} }
@@ -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<String>();
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"); }
}
@@ -0,0 +1,250 @@
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 record Session(ProjectCredentials.Credential credential, AtomicBoolean initialized, java.util.concurrent.atomic.AtomicLong lastSeen) { }
private final Map<String, Session> sessions = new ConcurrentHashMap<>();
private final ProjectCredentials credentials = new ProjectCredentials();
private volatile String instanceId;
public ProjectCredentials credentials() { return credentials; }
public String instanceId() { return instanceId; }
public synchronized void activateCredential(String instance, ProjectCredentials.Credential credential) {
if (server == null || !Objects.equals(instanceId, instance)) throw new IllegalStateException("Studio instance changed");
credential.activate();
}
public String catalogFingerprint() { return tools.catalogFingerprint(); }
public boolean connected(java.nio.file.Path root) {
long now = System.nanoTime();
return sessions.values().stream().anyMatch(s -> s.initialized.get() && s.credential.active() && s.credential.root().equals(root)
&& now - s.lastSeen.get() < TimeUnit.SECONDS.toNanos(10));
}
private final SecureRandom random = new SecureRandom();
private HttpServer server;
private ExecutorService executor;
private ScheduledExecutorService deadlines;
private volatile Connection connection;
private final java.util.List<Runnable> 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)
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.tools = Objects.requireNonNull(tools);
}
public void start() throws IOException {
synchronized (this) {
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 {
instanceId = UUID.randomUUID().toString();
connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"));
deadlines = timers;
next.createContext("/mcp", this::handle);
next.setExecutor(workers);
next.start();
timers.scheduleWithFixedDelay(() -> connectionListeners.forEach(LocalMcpServer::notifyConnectionListener), 2, 2, TimeUnit.SECONDS);
executor = workers; server = next;
} catch (RuntimeException failure) {
next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null;
throw failure;
}
}
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
}
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 void close() {
synchronized (this) {
if (server == null) return;
connection = null; server.stop(0); server = null;
sessions.clear(); credentials.clear(); executor.shutdownNow(); deadlines.shutdownNow();
}
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
}
/** Public endpoint metadata contains no credential. */
public static final class Connection {
private final URI endpoint;
private Connection(URI endpoint) { this.endpoint = endpoint; }
public URI endpoint() { return endpoint; }
@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");
var credential = credentials.authenticate(authorization);
if (credential == null) {
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");
var session = sessionId == null ? null : sessions.get(sessionId);
if (session != null && session.credential != credential) { empty(exchange, 403); return; }
AtomicBoolean initialized = session == null ? null : session.initialized;
if (session != null) session.lastSeen.set(System.nanoTime());
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) {
sessions.values().removeIf(s -> !s.credential.active());
if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; }
sessionId = secret(); sessions.put(sessionId, new Session(credential, new AtomicBoolean(), new java.util.concurrent.atomic.AtomicLong(System.nanoTime())));
}
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", McpConnectionGuide.INSTRUCTIONS);
result.putObject("_meta").put("instanceId", instanceId).put("projectRoot", credential.root().toString()).put("catalogFingerprint", tools.catalogFingerprint());
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");
var arguments = params.get("arguments");
if (arguments == null || !arguments.path("projectRoot").isTextual()) throw new IllegalArgumentException("Missing root");
java.nio.file.Path requested;
try { requested = java.nio.file.Path.of(arguments.path("projectRoot").asText());
if (!requested.isAbsolute()) throw new IllegalArgumentException("Relative root");
requested = requested.toRealPath();
} catch (java.io.IOException | RuntimeException invalid) { throw new IllegalArgumentException("Invalid root"); }
if (!credential.active() || !credential.root().equals(requested)) {
yield McpToolResult.failure(mapper, new p.studio.api.automation.AutomationFailure(
p.studio.api.automation.AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Connection is bound to another project or no longer authorized")).wire();
}
yield tools.call(params.get("name").asText(), 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() : "<multiple-headers>";
}
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); }
}
@@ -0,0 +1,66 @@
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;
/** Projects connection liveness and permanent setup independently of task authority. */
public final class McpConnectionGuide implements AgentConnectionGuide {
public static final String INSTRUCTIONS = """
Use the Studio tools for this project. Wait for the developer to grant access in DEV, then acquire control.
The installed Studio connector discovers the connection automatically; do not write transport scripts or copy tokens.
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.
After Studio restart, wait for a fresh human grant. The connector reconnects automatically; old task identities are invalid.
""";
private final LocalMcpServer server;
private final ProjectAccessRegistry projects;
private final ObjectMapper mapper;
private final p.studio.api.automation.AgentIntegrationPreparation preparation;
public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper) {
this(server, projects, mapper, new StudioAgentPreparation(p.studio.app.install.ManagedStudioInstallation.defaultRoot(), mapper));
}
public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper,
p.studio.api.automation.AgentIntegrationPreparation preparation) {
this.server = server; this.projects = projects; this.mapper = mapper; this.preparation = preparation;
}
@Override public boolean supportsPreparation() { return true; }
@Override public Optional<String> 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);
return "Run the installed Studio in mcp --project mode for " + canonical + "\n" + INSTRUCTIONS;
}
@Override public p.studio.api.automation.AgentIntegrationPreparation.Result prepare(Path root) {
return preparation.prepare(projects.requireOpenRoot(root));
}
@Override public p.studio.api.automation.AgentIntegrationPreparation.Result preparationStatus(Path root) {
return preparation.status(projects.requireOpenRoot(root));
}
@Override public State state(Path root) {
try {
Path canonical = projects.requireOpenRoot(root);
if (!server.isRunning()) return State.UNAVAILABLE;
if (server.connected(canonical)) return State.CONNECTED;
var control = projects.requireAutomation(canonical).snapshot().state();
return control == p.studio.api.automation.ControlState.AGENT_WORKING ? State.RECONNECTING : State.WAITING_FOR_ACCESS;
} catch (RuntimeException unavailable) { return State.UNAVAILABLE; }
}
@Override public OperationSubscription subscribe(Runnable changed) { return server.onConnectionChanged(changed); }
}
@@ -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<String, Function<JsonNode, McpToolResult>> 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<Map<String, Object>>() {})))));
}
}
@@ -0,0 +1,34 @@
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<String, Function<JsonNode, McpToolResult>> 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())))),
"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();
}
}
@@ -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<String, Function<JsonNode, McpToolResult>> handlers(TaskTools tools, ObjectMapper mapper, boolean headlessAvailable) {
var handlers = new LinkedHashMap<String, Function<JsonNode, McpToolResult>>();
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<String, Object> 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<String, Object> input(JsonNode input) {
var normalized = new LinkedHashMap<String, Object>();
for (var name : List.of("up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select", "touch"))
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(); }
}
@@ -0,0 +1,47 @@
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<String, JsonNode> 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<String, JsonNode>();
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<String> names() { return definitions.keySet(); }
public String fingerprint() {
try {
var digest = java.security.MessageDigest.getInstance("SHA-256");
digest.update(LocalMcpServer.PROTOCOL_VERSION.getBytes(java.nio.charset.StandardCharsets.UTF_8));
definitions.keySet().stream().sorted().forEach(name -> digest.update(descriptor(name).toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)));
return java.util.HexFormat.of().formatHex(digest.digest());
} catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
}
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");
}
}
@@ -0,0 +1,44 @@
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<String, Function<JsonNode, McpToolResult>> handlers;
public McpToolRegistry(McpToolCatalog catalog, ObjectMapper mapper, Map<String, Function<JsonNode, McpToolResult>> 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 String catalogFingerprint() { return catalog.fingerprint(); }
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 (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;
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"));
}
}
}
@@ -0,0 +1,49 @@
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;
}
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);
wire.putArray("content").addObject().put("type", "text").put("text", data.toString());
return new McpToolResult(wire);
}
}
@@ -0,0 +1,79 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.*;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
/** Local discovery data is untrusted until paths, permissions and live identity are verified. */
public final class ProjectConnectionFiles {
public static final String RELATIVE = ".studio/mcp/connection.json";
private static final Set<java.nio.file.attribute.PosixFilePermission> FILE_MODE = PosixFilePermissions.fromString("rw-------");
private ProjectConnectionFiles() { }
public static Path directory(Path root) throws IOException {
Path studio = root.resolve(".studio"), directory = studio.resolve("mcp");
safeDirectory(studio, false); safeDirectory(directory, true); return directory;
}
private static void safeDirectory(Path path, boolean privateDirectory) throws IOException {
if (!Files.exists(path, NOFOLLOW_LINKS)) Files.createDirectory(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
if (Files.isSymbolicLink(path) || !Files.isDirectory(path, NOFOLLOW_LINKS)) throw new IOException("Unsafe connection directory");
if (privateDirectory) requirePrivate(path, true);
}
public static void requirePrivate(Path path, boolean directory) throws IOException {
if (Files.isSymbolicLink(path) || !(directory ? Files.isDirectory(path, NOFOLLOW_LINKS) : Files.isRegularFile(path, NOFOLLOW_LINKS)))
throw new IOException("Unsafe connection file");
var expected = directory ? PosixFilePermissions.fromString("rwx------") : FILE_MODE;
if (!Files.getPosixFilePermissions(path, NOFOLLOW_LINKS).equals(expected)
|| !Files.getOwner(path, NOFOLLOW_LINKS).equals(Files.getOwner(Path.of(System.getProperty("user.home")))))
throw new IOException("Connection permissions must be restricted to the current user");
}
public static void atomicPrivateWrite(Path target, byte[] bytes) throws IOException {
if (Files.exists(target, NOFOLLOW_LINKS)) requirePrivate(target, false);
var temp = Files.createTempFile(target.getParent(), ".connection-", ".tmp", PosixFilePermissions.asFileAttribute(FILE_MODE));
try { Files.write(temp, bytes); Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
finally { Files.deleteIfExists(temp); }
}
public static boolean tracked(Path root, String relative) throws IOException {
try {
var process = new ProcessBuilder("git", "-C", root.toString(), "ls-files", "-z", "--", relative).redirectError(ProcessBuilder.Redirect.DISCARD).start();
if (!process.waitFor(5, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Git check timed out"); }
if (process.exitValue() != 0 && process.exitValue() != 128) throw new IOException("Cannot verify file tracking");
return process.getInputStream().read() != -1;
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Git check interrupted"); }
}
public static void ignore(Path root, String relative) throws IOException {
Path path = root.resolve(".gitignore");
if (Files.isSymbolicLink(path)) throw new IOException("Unsafe ignore file");
String old = Files.exists(path) ? Files.readString(path) : "";
String rule = "/" + relative;
if (old.lines().anyMatch(rule::equals)) return;
Files.writeString(path, old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + rule + "\n");
}
public static Descriptor read(Path root, ObjectMapper mapper) throws IOException {
Path path = root.resolve(RELATIVE);
if (Files.isSymbolicLink(root.resolve(".studio"))) throw new IOException("Unsafe discovery path");
requirePrivate(path.getParent(), true); requirePrivate(path, false);
byte[] bytes;
try (var input = Files.newInputStream(path, NOFOLLOW_LINKS)) { bytes = input.readNBytes(16 * 1024 + 1); }
if (bytes.length > 16 * 1024) throw new IOException("Connection descriptor too large");
var json = mapper.readTree(bytes);
if (json == null || !json.path("schemaVersion").isIntegralNumber() || !json.path("schemaVersion").canConvertToInt() || json.path("schemaVersion").asInt(-1) != 1) throw new IOException("Unsupported connection schema");
for (String field : Set.of("instanceId", "projectRoot", "endpoint", "credential", "catalogFingerprint"))
if (!json.path(field).isTextual() || json.path(field).asText().isBlank()) throw new IOException("Invalid connection descriptor");
try {
if (!Path.of(json.path("projectRoot").asText()).equals(root)) throw new IOException("Connection project mismatch");
URI endpoint = URI.create(json.path("endpoint").asText());
if (!"http".equals(endpoint.getScheme()) || !"127.0.0.1".equals(endpoint.getHost()) || endpoint.getPort() < 1
|| endpoint.getPort() > 65535 || !"/mcp".equals(endpoint.getRawPath()) || endpoint.getRawQuery() != null
|| endpoint.getRawFragment() != null || endpoint.getUserInfo() != null) throw new IOException("Invalid loopback endpoint");
return new Descriptor(endpoint, json.path("instanceId").asText(), json.path("credential").asText(), json.path("catalogFingerprint").asText());
} catch (IllegalArgumentException invalid) { throw new IOException("Invalid connection descriptor"); }
}
public record Descriptor(URI endpoint, String instanceId, String credential, String catalogFingerprint) {
@Override public String toString() { return "ProjectConnectionDescriptor[REDACTED]"; }
}
}
@@ -0,0 +1,52 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.api.automation.AutomationConnectionLifecycle;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
/** The lock inode outlives a publication. Its OS lock, not a stale PID/file, establishes ownership. */
public final class ProjectConnectionPublisher implements AutomationConnectionLifecycle {
private final LocalMcpServer server;
private final ObjectMapper mapper;
public ProjectConnectionPublisher(LocalMcpServer server, ObjectMapper mapper) { this.server = server; this.mapper = mapper; }
@Override public Publication prepare(Path projectRoot) throws Exception {
Path root = projectRoot.toRealPath();
final String instance = server.instanceId();
final var endpoint = server.connection().endpoint();
if (ProjectConnectionFiles.tracked(root, ProjectConnectionFiles.RELATIVE)) throw new IllegalStateException("Connection file is tracked");
ProjectConnectionFiles.ignore(root, ".studio/mcp/");
Path directory = ProjectConnectionFiles.directory(root), lockPath = directory.resolve("publication.lock");
if (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS)) ProjectConnectionFiles.requirePrivate(lockPath, false);
var channel = FileChannel.open(lockPath, Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS),
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
FileLock lock;
try { lock = channel.tryLock(); if (lock == null) throw new AutomationConnectionLifecycle.OwnershipConflict(); }
catch (OverlappingFileLockException conflict) { channel.close(); throw new AutomationConnectionLifecycle.OwnershipConflict(); }
catch (Exception conflict) { channel.close(); throw conflict; }
var credential = server.credentials().prepare(root);
return new Publication() {
private boolean published, closed;
public void publish() throws Exception {
var value = mapper.createObjectNode().put("schemaVersion", 1).put("instanceId", instance)
.put("projectRoot", root.toString()).put("endpoint", endpoint.toString())
.put("credential", credential.secret()).put("catalogFingerprint", server.catalogFingerprint());
ProjectConnectionFiles.atomicPrivateWrite(directory.resolve("connection.json"), mapper.writeValueAsBytes(value)); published = true;
}
public void activate() { server.activateCredential(instance, credential); }
public void invalidate() { credential.invalidate(); }
public synchronized void close() throws Exception {
if (closed) return; closed = true; invalidate();
try {
if (published && Files.exists(directory.resolve("connection.json"), LinkOption.NOFOLLOW_LINKS)) {
var current = ProjectConnectionFiles.read(root, mapper);
if (instance.equals(current.instanceId()) && credential.secret().equals(current.credential()))
Files.delete(directory.resolve("connection.json"));
}
} finally { try { lock.release(); } finally { channel.close(); } }
}
};
}
}
@@ -0,0 +1,42 @@
package p.studio.app.mcp;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/** Memory-only authentication; never a substitute for the Core grant/task checks. */
public final class ProjectCredentials {
private final Map<String, Credential> credentials = new ConcurrentHashMap<>();
public Credential prepare(Path root) {
byte[] bytes = new byte[32]; new SecureRandom().nextBytes(bytes);
var credential = new Credential(root, Base64.getUrlEncoder().withoutPadding().encodeToString(bytes));
credentials.put(credential.secret, credential); return credential;
}
public Credential authenticate(String header) {
if (header == null || !header.startsWith("Bearer ")) return null;
String token = header.substring(7);
var found = credentials.get(token);
return found != null && found.active && MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
found.secret.getBytes(StandardCharsets.UTF_8)) ? found : null;
}
public void clear() { credentials.values().forEach(Credential::invalidate); credentials.clear(); }
public final class Credential {
private final Path root;
private final String secret;
private volatile boolean active;
private boolean invalidated;
private Credential(Path root, String secret) { this.root = root; this.secret = secret; }
public Path root() { return root; }
public String secret() { return secret; }
public synchronized void activate() {
if (invalidated) throw new IllegalStateException("Credential invalidated");
active = true;
}
public synchronized void invalidate() { active = false; invalidated = true; credentials.remove(secret, this); }
public boolean active() { return active; }
@Override public String toString() { return "ProjectCredential[REDACTED]"; }
}
}
@@ -0,0 +1,124 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.api.automation.AgentIntegrationPreparation;
import p.studio.app.install.ManagedStudioInstallation;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.tomlj.Toml;
/** Only the managed entry is edited; unrelated client configuration remains byte-for-byte intact. */
public final class StudioAgentPreparation implements AgentIntegrationPreparation {
private final Path installation;
private final ObjectMapper mapper;
private final Map<Path, Result> preparationFailures = new java.util.concurrent.ConcurrentHashMap<>();
private static final String BEGIN = "# Studio managed MCP entry ";
private static final String END = "# End Studio managed MCP entry\n";
public StudioAgentPreparation(Path installation, ObjectMapper mapper) { this.installation = installation; this.mapper = mapper; }
@Override public synchronized Result prepare(Path projectRoot) {
var result = prepareLocal(projectRoot);
Path key = preparationKey(projectRoot);
if (result.ready()) preparationFailures.remove(key); else preparationFailures.put(key, result);
return result;
}
private Result prepareLocal(Path projectRoot) {
try {
Path root = projectRoot.toRealPath();
if (!Files.isRegularFile(root.resolve("prometeu.json"))) return new Result(false, "Project manifest not found.");
if (ProjectConnectionFiles.tracked(root, ".codex/config.toml"))
return new Result(false, "Client configuration is tracked. Keep machine-specific registration local before preparing this project.");
Path directory = root.resolve(".codex"), config = directory.resolve("config.toml");
if (Files.isSymbolicLink(directory) || Files.isSymbolicLink(config)) return new Result(false, "Client configuration path is unsafe.");
String old = Files.exists(config) ? Files.readString(config) : "";
String next = merge(old, entry(root));
ManagedStudioInstallation.ensureAvailable(installation);
Files.createDirectories(directory);
ProjectConnectionFiles.ignore(root, ".codex/config.toml");
ProjectConnectionFiles.ignore(root, ".studio/mcp/");
if (!old.equals(next)) {
int previous = old.indexOf(BEGIN);
if (previous >= 0) {
ProjectConnectionFiles.ignore(root, ".codex/.studio-mcp.previous.toml");
String owned = old.substring(previous, old.indexOf(END, previous) + END.length());
ProjectConnectionFiles.atomicPrivateWrite(directory.resolve(".studio-mcp.previous.toml"), owned.getBytes(StandardCharsets.UTF_8));
}
Path temporary = Files.createTempFile(directory, ".studio-config-", ".tmp", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
try { Files.writeString(temporary, next); Files.move(temporary, config, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
finally { Files.deleteIfExists(temporary); }
}
Path studio = root.resolve(".studio");
if (Files.isSymbolicLink(studio)) throw new IllegalStateException("Unsafe setup directory");
Files.createDirectories(studio);
Path setup = studio.resolve("setup.json");
if (Files.isSymbolicLink(setup)) throw new IllegalStateException("Unsafe setup file");
var value = Files.exists(setup) ? mapper.readTree(Files.readAllBytes(setup)) : mapper.createObjectNode();
if (!(value instanceof com.fasterxml.jackson.databind.node.ObjectNode object)) throw new IllegalStateException("Invalid setup");
object.putObject("agentIntegration").put("schemaVersion", 1).put("enabled", true).put("clientProfile", "codex");
String setupText = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
if (!Files.exists(setup) || !Files.readString(setup).equals(setupText)) {
Path temporary = Files.createTempFile(studio, ".setup-", ".tmp");
try { Files.writeString(temporary, setupText); Files.move(temporary, setup, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
finally { Files.deleteIfExists(temporary); }
}
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Then grant access in DEV; no token copying or restart reconfiguration is needed.");
} catch (ManagedStudioInstallation.MissingInstallation missing) { return new Result(false, missing.getMessage()); }
catch (Conflict conflict) { return new Result(false, conflict.getMessage()); }
catch (Exception failure) { return new Result(false, "Preparation incomplete. Check the Studio installation and project/configuration permissions; existing client settings were not deliberately replaced."); }
}
@Override public Result status(Path projectRoot) {
var failure = preparationFailures.get(preparationKey(projectRoot));
if (failure != null) return failure;
try {
Path root = projectRoot.toRealPath(), config = root.resolve(".codex/config.toml");
if (Files.isSymbolicLink(config.getParent()) || Files.isSymbolicLink(config))
return new Result(false, "Unsafe client configuration path. Prepare the assistant after resolving it.");
if (!Files.isRegularFile(config)) return new Result(false, "Assistant setup is incomplete. Prepare the assistant for this project.");
String old = Files.readString(config);
if (!old.equals(merge(old, entry(root))) || !Files.isExecutable(installation.resolve("current/runtime/bin/java")))
return new Result(false, "Assistant setup is incomplete. Prepare the assistant from an installed Studio.");
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested.");
} catch (Conflict conflict) { return new Result(false, conflict.getMessage()); }
catch (Exception unavailable) { return new Result(false, "Assistant setup could not be verified. Prepare the assistant again."); }
}
private static Path preparationKey(Path root) {
try { return root.toRealPath(); }
catch (java.io.IOException missing) { return root.toAbsolutePath().normalize(); }
}
public String entry(Path root) throws Exception {
Path current = installation.resolve("current").toAbsolutePath();
return "[mcp_servers.prometeu_studio]\ncommand = " + quote(current.resolve("runtime/bin/java").toString())
+ "\nargs = " + mapper.writeValueAsString(List.of("-cp", current.resolve("lib/*").toString(), "p.studio.app.StudioLauncher", "mcp", "--project", root.toString()))
+ "\ncwd = " + quote(root.toString()) + "\nstartup_timeout_sec = 20\ntool_timeout_sec = 90\n";
}
private String quote(String text) throws Exception { return mapper.writeValueAsString(text); }
static String merge(String old, String entry) throws Exception {
if (Toml.parse(old).hasErrors()) throw new Conflict("Existing client TOML is invalid; repair it before preparation.");
String block = BEGIN + hash(entry) + "\n" + entry + END;
int start = old.indexOf(BEGIN), end = old.indexOf(END);
String next;
if (start >= 0) {
int body = old.indexOf('\n', start) + 1;
if (start > 0 && old.charAt(start - 1) != '\n' || body == 0 || end < body || old.indexOf(BEGIN, body) >= 0 || !old.substring(start + BEGIN.length(), body - 1).equals(hash(old.substring(body, end))))
throw new Conflict("The Studio MCP entry was edited. Resolve the managed-entry conflict explicitly.");
next = old.substring(0, start) + block + old.substring(end + END.length());
} else {
if (end >= 0 || Toml.parse(old).contains("mcp_servers.prometeu_studio")) throw new Conflict("A user-owned Studio MCP entry already exists; resolve it explicitly.");
next = old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + block;
}
if (Toml.parse(next).hasErrors()) throw new Conflict("Client configuration conflicts with the Studio entry; nothing was overwritten.");
var actual = Toml.parse(next).getTable("mcp_servers.prometeu_studio");
var expected = Toml.parse(entry).getTable("mcp_servers.prometeu_studio");
if (actual == null || expected == null || !actual.keySet().equals(expected.keySet())
|| !Objects.equals(actual.getString("command"), expected.getString("command"))
|| !Objects.equals(actual.getString("cwd"), expected.getString("cwd"))
|| !Objects.equals(actual.getLong("startup_timeout_sec"), expected.getLong("startup_timeout_sec"))
|| !Objects.equals(actual.getLong("tool_timeout_sec"), expected.getLong("tool_timeout_sec"))
|| actual.getArray("args") == null || !actual.getArray("args").toList().equals(expected.getArray("args").toList()))
throw new Conflict("The managed Studio table conflicts with other client settings; resolve it explicitly.");
return next;
}
private static String hash(String text) throws Exception { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); }
private static final class Conflict extends Exception { Conflict(String text) { super(text); } }
}
@@ -0,0 +1,170 @@
package p.studio.app.mcp.stdio;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import p.studio.app.mcp.*;
import java.io.*;
import java.net.http.*;
import java.nio.file.*;
import java.time.Duration;
import java.util.*;
/** Owns only HTTP transport. Never retries a tools/call or creates task authority. */
final class StudioMcpConnection implements AutoCloseable {
private final Path root;
private final ObjectMapper mapper;
private final McpToolCatalog catalog;
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).followRedirects(HttpClient.Redirect.NEVER).build();
private ProjectConnectionFiles.Descriptor descriptor;
private String session;
private Set<String> available = Set.of();
// Diagnostic correlation only: Core remains the sole validator of task authority.
private final LinkedHashMap<String, String> observedTaskInstances = new LinkedHashMap<>();
private long sequence;
private volatile String status = "WAITING_FOR_ACCESS";
StudioMcpConnection(Path root, ObjectMapper mapper, McpToolCatalog catalog) { this.root = root; this.mapper = mapper; this.catalog = catalog; }
String status() { return status; }
synchronized void probe() {
try { connect(); exchange("ping", mapper.createObjectNode(), true, 3); status = "CONNECTED"; }
catch (Exception failure) { disconnect(); }
}
synchronized JsonNode call(String tool, JsonNode arguments) {
boolean dispatched = false;
try {
catalog.validateArguments(tool, arguments);
try {
if (!Path.of(arguments.path("projectRoot").asText()).toRealPath().equals(root))
return failure("OUTSIDE_PROJECT_SCOPE", "The connector is bound to another project.");
} catch (IOException inaccessible) { return failure("INVALID_REQUEST", "Project root cannot be resolved."); }
connect();
String taskInstance = observedTaskInstances.get(arguments.path("taskId").asText());
if (tool.equals("studio_operation_get") && taskInstance != null && !taskInstance.equals(descriptor.instanceId()))
return failure("OUTCOME_UNKNOWN", "Studio restarted; this task's in-memory receipts are unavailable. Obtain a fresh grant/task and decide the next intent explicitly; do not replay the old operation.");
if (!available.contains(tool)) return failure("UNSUPPORTED_CAPABILITY", "The live Studio does not provide this tool.");
var params = mapper.createObjectNode().put("name", tool).set("arguments", arguments);
dispatched = true;
var response = exchange("tools/call", params, true, 70);
if (response.has("error")) throw new ProtocolFailure(response.get("error"));
status = "CONNECTED";
var result = response.required("result");
if (tool.equals("studio_control_acquire") && !result.path("isError").asBoolean()) {
String task = result.path("structuredContent").path("value").path("taskId").asText();
if (!task.isBlank()) {
observedTaskInstances.put(task, descriptor.instanceId());
if (observedTaskInstances.size() > 64) observedTaskInstances.remove(observedTaskInstances.keySet().iterator().next());
}
}
return result;
} catch (ProtocolFailure protocol) { throw protocol;
} catch (IllegalArgumentException invalid) {
return failure("INVALID_REQUEST", "Invalid tool arguments or project root.");
} catch (Exception unavailable) {
disconnect();
var result = failure(dispatched ? "OUTCOME_UNKNOWN" : status,
dispatched ? "Response unavailable; do not replay. For the same authorized task, look up operationId/clientRequestId. After Studio restart, obtain a new grant; old receipts may be unavailable."
: guidance());
if (dispatched && arguments != null && arguments.path("clientRequestId").isTextual())
((ObjectNode) result.path("structuredContent").path("error")).put("clientRequestId", arguments.path("clientRequestId").asText());
((ObjectNode) result.path("content").get(0)).put("text", result.path("structuredContent").toString());
return result;
}
}
private String guidance() {
return switch (status) {
case "VERSION_INCOMPATIBLE" -> "Studio and its installed connector are incompatible; update the installation.";
case "STALE_CONNECTION" -> "Connection credentials are stale or invalid; grant access again in DEV.";
case "INVALID_DESCRIPTOR" -> "Project connection data or permissions are invalid; prepare the project again.";
default -> "Open Studio and this project, then grant access in DEV. The connection will be discovered without restarting this client.";
};
}
private void connect() throws Exception {
ProjectConnectionFiles.Descriptor next;
try { next = ProjectConnectionFiles.read(root, mapper); }
catch (NoSuchFileException absent) { status = "WAITING_FOR_ACCESS"; throw absent; }
catch (IOException invalid) {
status = Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)) ? "INVALID_DESCRIPTOR" : "WAITING_FOR_ACCESS";
throw invalid;
}
if (!catalog.fingerprint().equals(next.catalogFingerprint())) { status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible catalog"); }
if (session != null && next.equals(descriptor)) return;
descriptor = next; session = null; status = "RECONNECTING";
var params = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION);
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "studio-project-connector").put("version", "1");
var result = exchange("initialize", params, true, 5).required("result");
if (!LocalMcpServer.PROTOCOL_VERSION.equals(result.path("protocolVersion").asText())
|| !catalog.fingerprint().equals(result.path("_meta").path("catalogFingerprint").asText())) {
status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible protocol");
}
if (!next.instanceId().equals(result.path("_meta").path("instanceId").asText())
|| !root.toString().equals(result.path("_meta").path("projectRoot").asText())) {
status = "STALE_CONNECTION"; throw new IOException("Wrong instance");
}
exchange("notifications/initialized", mapper.createObjectNode(), false, 5);
var descriptors = exchange("tools/list", mapper.createObjectNode(), true, 5).path("result").path("tools");
if (!descriptors.isArray()) throw new IOException("Invalid catalog");
var names = new HashSet<String>();
for (var tool : descriptors) {
String name = tool.path("name").asText();
if (!catalog.names().contains(name) || !catalog.descriptor(name).equals(tool) || !names.add(name)) {
status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible tools");
}
}
available = Set.copyOf(names); status = "CONNECTED";
}
private JsonNode exchange(String method, JsonNode params, boolean responseExpected, int seconds) throws Exception {
var message = mapper.createObjectNode().put("jsonrpc", "2.0").put("method", method);
if (responseExpected) message.put("id", ++sequence);
message.set("params", params);
var request = HttpRequest.newBuilder(descriptor.endpoint()).timeout(Duration.ofSeconds(seconds))
.header("Authorization", "Bearer " + descriptor.credential()).header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", LocalMcpServer.PROTOCOL_VERSION);
if (session != null) request.header("Mcp-Session-Id", session);
var pending = client.sendAsync(request.POST(HttpRequest.BodyPublishers.ofString(message.toString())).build(),
info -> boundedBody());
HttpResponse<byte[]> response;
try { response = pending.get(seconds, java.util.concurrent.TimeUnit.SECONDS); }
catch (Exception failure) { pending.cancel(true); throw failure; }
if (response.statusCode() != 200 && response.statusCode() != 202) {
if (response.statusCode() == 401 || response.statusCode() == 403 || response.statusCode() == 404) status = "STALE_CONNECTION";
throw new IOException("Connection rejected");
}
response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> session = value);
if (method.equals("initialize") && session == null) throw new IOException("Missing session identity");
if (!responseExpected) return mapper.nullNode();
var json = mapper.readTree(response.body());
if (json == null || !"2.0".equals(json.path("jsonrpc").asText()) || !json.path("id").isIntegralNumber() || !message.get("id").bigIntegerValue().equals(json.path("id").bigIntegerValue())
|| json.has("result") == json.has("error")) throw new IOException("Invalid response");
return json;
}
private static HttpResponse.BodySubscriber<byte[]> boundedBody() {
return new HttpResponse.BodySubscriber<>() {
final HttpResponse.BodySubscriber<byte[]> delegate = HttpResponse.BodySubscribers.ofByteArray();
java.util.concurrent.Flow.Subscription subscription;
long bytes;
public java.util.concurrent.CompletionStage<byte[]> getBody() { return delegate.getBody(); }
public void onSubscribe(java.util.concurrent.Flow.Subscription value) { subscription = value; delegate.onSubscribe(value); }
public void onNext(List<java.nio.ByteBuffer> buffers) {
for (var buffer : buffers) bytes += buffer.remaining();
if (bytes > 32L * 1024 * 1024) { subscription.cancel(); delegate.onError(new IOException("Response too large")); }
else delegate.onNext(buffers);
}
public void onError(Throwable failure) { delegate.onError(failure); }
public void onComplete() { delegate.onComplete(); }
};
}
private ObjectNode failure(String code, String message) {
var value = mapper.createObjectNode().put("isError", true);
var data = value.putObject("structuredContent").put("status", "error");
data.putObject("error").put("code", code).put("message", message);
value.putArray("content").addObject().put("type", "text").put("text", data.toString());
return value;
}
static final class ProtocolFailure extends RuntimeException {
final JsonNode error;
ProtocolFailure(JsonNode error) { super("Studio protocol error"); this.error = error.deepCopy(); }
}
private void disconnect() { if (status.equals("CONNECTED")) status = "RECONNECTING"; session = null; available = Set.of(); }
@Override public void close() { client.shutdownNow(); }
}
@@ -0,0 +1,83 @@
package p.studio.app.mcp.stdio;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import p.studio.app.mcp.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.concurrent.*;
/** A mode of Studio itself; no JavaFX, Spring, HTTP listener or agent runtime is started here. */
public final class StudioMcpStdio {
private StudioMcpStdio() { }
public static void main(String[] args) throws Exception {
if (args.length != 3 || !"mcp".equals(args[0]) || !"--project".equals(args[1]) || !Path.of(args[2]).isAbsolute())
throw new IllegalArgumentException("Usage: mcp --project <absolute-project-root>");
Path root = Path.of(args[2]).toRealPath();
if (!Files.isRegularFile(root.resolve("prometeu.json"))) throw new IllegalArgumentException("Project manifest not found");
run(root, System.in, System.out);
}
public static void run(Path root, InputStream input, OutputStream output) throws Exception {
var mapper = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
mapper.getFactory().setStreamReadConstraints(com.fasterxml.jackson.core.StreamReadConstraints.builder().maxStringLength(32 * 1024 * 1024).build());
var catalog = new McpToolCatalog(mapper);
var timer = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-discovery").factory());
try (var connection = new StudioMcpConnection(root, mapper, catalog)) {
timer.scheduleWithFixedDelay(connection::probe, 0, 2, TimeUnit.SECONDS);
boolean initialized = false, negotiated = false;
var line = new ByteArrayOutputStream(); int next;
while ((next = input.read()) != -1) {
if (next != '\n') {
if (line.size() >= 1024 * 1024) throw new IOException("MCP request exceeds limit");
line.write(next); continue;
}
JsonNode message;
try { message = mapper.readTree(StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(line.toByteArray())).toString()); }
catch (Exception malformed) { line.reset(); write(output, error(mapper, mapper.nullNode(), -32700, "Invalid JSON")); continue; }
line.reset();
if (message == null || !message.isObject() || !message.path("jsonrpc").isTextual() || !"2.0".equals(message.path("jsonrpc").asText())
|| !message.path("method").isTextual() || message.has("id") && !(message.path("id").isTextual() || message.path("id").isIntegralNumber())) {
write(output, error(mapper, mapper.nullNode(), -32600, "Invalid request")); continue;
}
String method = message.path("method").asText();
if (!message.has("id")) { if (negotiated && "notifications/initialized".equals(method)) initialized = true; continue; }
var id = message.get("id"); JsonNode result;
if (method.equals("initialize") && !negotiated) {
var params = message.path("params");
if (!params.path("protocolVersion").isTextual() || !params.path("capabilities").isObject() || !params.path("clientInfo").isObject()) {
write(output, error(mapper, id, -32602, "Invalid initialization")); continue;
}
var value = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION);
value.putObject("capabilities").putObject("tools").put("listChanged", false);
value.putObject("serverInfo").put("name", "prometeu-studio").put("version", "1");
value.put("instructions", McpConnectionGuide.INSTRUCTIONS + "\nProject root: " + root);
result = value; negotiated = true;
} else if (!initialized) { write(output, error(mapper, id, -32600, "Initialization required")); continue; }
else if (method.equals("ping")) result = mapper.createObjectNode();
else if (method.equals("tools/list")) {
var value = mapper.createObjectNode(); var tools = value.putArray("tools");
catalog.names().forEach(name -> tools.add(catalog.descriptor(name))); result = value;
} else if (method.equals("tools/call")) {
String tool = message.path("params").path("name").asText();
var arguments = message.path("params").path("arguments");
try { catalog.validateArguments(tool, arguments); }
catch (IllegalArgumentException invalid) { write(output, error(mapper, id, -32602, "Invalid tool arguments")); continue; }
try { result = connection.call(tool, arguments); }
catch (StudioMcpConnection.ProtocolFailure protocol) {
var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); reply.set("error", protocol.error);
write(output, reply); continue;
}
} else { write(output, error(mapper, id, -32601, "Method not found")); continue; }
var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); reply.set("result", result); write(output, reply);
}
} finally { timer.shutdownNow(); }
}
private static JsonNode error(ObjectMapper mapper, JsonNode id, int code, String text) {
var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id);
reply.putObject("error").put("code", code).put("message", text); return reply;
}
private static void write(OutputStream output, JsonNode value) throws IOException {
output.write(value.toString().getBytes(StandardCharsets.UTF_8)); output.write('\n'); output.flush();
}
}
@@ -39,6 +39,9 @@ public final class ExecutorOperationExecutor implements OperationExecutor {
private final String summary; private final String summary;
private final Callable<R> operation; private final Callable<R> operation;
private final CompletableFuture<R> completion = new CompletableFuture<>(); private final CompletableFuture<R> completion = new CompletableFuture<>();
private final CompletableFuture<Void> termination = new CompletableFuture<>();
private final Object workerLifecycle = new Object();
private boolean started;
private final CopyOnWriteArrayList<Consumer<OperationSnapshot>> subscribers = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<Consumer<OperationSnapshot>> subscribers = new CopyOnWriteArrayList<>();
private final AtomicReference<OperationSnapshot> snapshot; private final AtomicReference<OperationSnapshot> snapshot;
private volatile Future<?> task; private volatile Future<?> task;
@@ -62,12 +65,19 @@ public final class ExecutorOperationExecutor implements OperationExecutor {
} }
} }
return null; return null;
}); }) {
@Override public void run() {
synchronized (workerLifecycle) { started = true; }
try { super.run(); }
finally { termination.complete(null); }
}
};
task = submitted; task = submitted;
try { try {
transition(OperationState.RUNNING, summary); transition(OperationState.RUNNING, summary);
executor.execute(submitted); executor.execute(submitted);
} catch (RuntimeException failure) { } catch (RuntimeException failure) {
termination.complete(null);
if (transitionTerminal(OperationState.FAILED, failureSummary(failure))) { if (transitionTerminal(OperationState.FAILED, failureSummary(failure))) {
completion.completeExceptionally(failure); completion.completeExceptionally(failure);
} }
@@ -89,6 +99,8 @@ public final class ExecutorOperationExecutor implements OperationExecutor {
return completion; return completion;
} }
@Override public CompletionStage<Void> termination() { return termination; }
@Override @Override
public boolean cancel() { public boolean cancel() {
while (true) { while (true) {
@@ -99,8 +111,9 @@ public final class ExecutorOperationExecutor implements OperationExecutor {
final OperationSnapshot cancelled = new OperationSnapshot(id, OperationState.CANCELLED, Instant.now(), summary); final OperationSnapshot cancelled = new OperationSnapshot(id, OperationState.CANCELLED, Instant.now(), summary);
if (snapshot.compareAndSet(current, cancelled)) { if (snapshot.compareAndSet(current, cancelled)) {
final Future<?> submitted = task; final Future<?> submitted = task;
if (submitted != null) { synchronized (workerLifecycle) {
submitted.cancel(true); if (submitted != null) submitted.cancel(true);
if (!started) termination.complete(null);
} }
completion.cancel(false); completion.cancel(false);
publish(cancelled); publish(cancelled);
@@ -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<String> 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));
}
}
@@ -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<ProjectReference, ProjectLocalStudioSetup> setup;
private final HeadlessLimits limits;
public HeadlessProcessGateway(ObjectMapper mapper, Function<ProjectReference, ProjectLocalStudioSetup> setup) {
this(mapper, setup, HeadlessLimits.defaults());
}
public HeadlessProcessGateway(ObjectMapper mapper, Function<ProjectReference, ProjectLocalStudioSetup> 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<String>(); 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; }
}
}
@@ -0,0 +1,320 @@
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<JsonNode> greeting = new CompletableFuture<>();
private final Map<String, Pending> pending = new ConcurrentHashMap<>();
private final Set<ProcessHandle> 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<Pending> advance = new AtomicReference<>();
private final Deque<String> stderr = new ArrayDeque<>();
private volatile boolean closing;
private CompletableFuture<Void> 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<String, Object> 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<String, Object>(); 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<TrackedOperation.Progress> 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<String>();
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);
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<Void> 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());
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<TrackedOperation.Progress> 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);
Map<String, Object> runtimeError = mapper.convertValue(error, new com.fasterxml.jackson.core.type.TypeReference<>() {});
item.result.completeExceptionally(new AutomationException(new AutomationFailure(code,
"Runtime " + error.path("code").asText() + ": " + error.path("message").asText(), runtimeError)));
} 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> T await(CompletableFuture<T> 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> T awaitUninterruptibly(CompletableFuture<T> 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<TrackedOperation.Progress> observer;
final CompletableFuture<JsonNode> result = new CompletableFuture<>();
final AtomicBoolean cancelled = new AtomicBoolean();
volatile long completed;
JsonNode params;
Pending(String command, Long frames, Consumer<TrackedOperation.Progress> observer) { this.command = command; this.frames = frames; this.observer = observer; }
}
}
@@ -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<String> 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<String>();
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); }
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,193 @@
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<Void>();
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<Void>();
Platform.runLater(() -> { try { work.run(); completed.complete(null); } catch (Throwable failure) { completed.completeExceptionally(failure); } });
completed.get(10, TimeUnit.SECONDS);
}
static void awaitWaiting(AutomationSession authority) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (authority.snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(5);
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
}
@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();
});
awaitWaiting(authority);
fx(() -> {
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<Void> 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);
});
awaitWaiting(authority);
} 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 preparesConnectionWithoutGrantAndRemainsAvailableWhenTransportStops() throws Exception {
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
var projects = new p.studio.core.project.ProjectAccessRegistry();
var prepared = new CompletableFuture<Void>();
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, project -> {
prepared.complete(null);
return new p.studio.api.automation.AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once.");
});
server.start();
try {
fx(() -> {
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();
});
prepared.get(5, TimeUnit.SECONDS);
assertEquals(ControlState.MANUAL, authority.snapshot().state());
server.close();
fx(() -> assertFalse(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
server.start(); authority.grant(false).toCompletableFuture().join();
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
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(); });
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");
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 = ""; }
}
}
@@ -21,13 +21,24 @@ class StudioApplicationConfigurationTest {
.headless(true) .headless(true)
.run(); .run();
final ExecutorService executor = context.getBean(ExecutorService.class); final ExecutorService executor = context.getBean(ExecutorService.class);
final var mcp = context.getBean(p.studio.app.mcp.LocalMcpServer.class);
try (context) { try (context) {
assertNotNull(context.getBean(StudioUiFactory.class)); assertNotNull(context.getBean(StudioUiFactory.class));
assertNotNull(context.getBean(PackerWorkspaceService.class)); assertNotNull(context.getBean(PackerWorkspaceService.class));
assertNotNull(context.getBean(OperationExecutor.class)); assertNotNull(context.getBean(OperationExecutor.class));
assertFalse(context.getClass().getName().contains("WebServer")); assertFalse(context.getClass().getName().contains("WebServer"));
assertFalse(executor.isShutdown()); assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
org.junit.jupiter.api.Assertions.assertEquals(17, tools.size());
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"));
assertTrue(tools.toString().contains("studio_headless_boot"));
} }
assertTrue(executor.isShutdown()); assertTrue(executor.isShutdown());
assertFalse(mcp.isRunning());
} }
} }
@@ -0,0 +1,195 @@
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:"));
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")));
}
@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());
}
}
@@ -0,0 +1,149 @@
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");
verifyRuntimeCatalogs(provider.getClass().getClassLoader());
if (arguments.length == 1 && arguments[0].equals("--catalog-only")) return;
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.stdout());
check(result.diagnostics().stream().noneMatch(issue -> issue.isError()), "Example must compile without errors");
check(result.bytecodeBytes().length > 0, "Example must produce bytecode");
verifyExternalSources(provider.getClass().getClassLoader());
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);
}
private static void verifyRuntimeCatalogs(ClassLoader loader) throws Exception {
var names = java.util.List.of("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv", "runtime-catalog.properties");
var compiler = new java.util.HashMap<String, byte[]>();
for (var name : names) {
for (var owner : java.util.List.of("compiler", "pbs-sdk")) {
var resource = loader.getResource("runtime-catalog/" + owner + "/" + name);
check(resource != null && resource.getProtocol().equals("jar"), "Missing installed catalog: " + owner + "/" + name);
try (var stream = resource.openStream()) {
var bytes = stream.readAllBytes();
if (owner.equals("compiler")) compiler.put(name, bytes);
else check(java.util.Arrays.equals(compiler.get(name), bytes), "Compiler/SDK contract mismatch: " + name);
}
}
}
var properties = new java.util.Properties();
properties.load(new java.io.ByteArrayInputStream(compiler.get("runtime-catalog.properties")));
check(properties.getProperty("runtime.revision").matches("[0-9a-f]{40}"), "Missing target revision");
for (var name : names.subList(0, 2)) {
var digest = java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(compiler.get(name)));
check(digest.equals(properties.getProperty(name + ".sha256")), "Packaged catalog hash mismatch: " + name);
}
System.out.println("Installed compiler/SDK catalog identity verified: " + properties.getProperty("runtime.revision"));
}
private static void verifyExternalSources(ClassLoader loader) throws Exception {
var resource = loader.getResource("game/stdlib/1/sdk/gfx/main.pbs");
check(resource != null && resource.getProtocol().equals("jar"), "SDK must be read from a JAR URL");
check(p.studio.lsp.services.compiler.CompilerLanguageServiceBridge.class.getProtectionDomain()
.getCodeSource().getLocation().getPath().endsWith(".jar"), "LSP bridge must come from installed JAR");
Path root = Files.createDirectory(Path.of("external-sources")).toRealPath();
Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"), """
{"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
String source = "import { Gfx } from @sdk:gfx;\nfn main() -> void { Gfx.clear(0); }\n";
Path file = Files.writeString(root.resolve("src/main.pbs"), source);
Files.writeString(root.resolve("src/mod.barrel"), "pub fn main() -> void;\n");
var context = new p.studio.lsp.messages.LspProjectContext("installed", "pbs", root);
var bridge = new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge();
try (var registry = new p.studio.lsp.services.compiler.ExternalSourceRegistry()) {
String consumer = registry.connect(null, false);
int[] sdkUse = position(source, "Gfx.clear", "Gfx.".length());
var targets = bridge.navigation(context, file.toUri().toString(), source, sdkUse[0], sdkUse[1], registry, consumer).locations();
check(targets.size() == 1, "Packaged SDK definition must resolve");
String uri = targets.getFirst().uri();
check(uri.startsWith("prometeu-source:"), "SDK must use a virtual URI");
var content = registry.read(consumer, uri);
check(content.descriptor().readOnly() && content.descriptor().origin().equals("bundled"), "Bundled SDK must be read-only");
try (var stream = resource.openStream()) {
check(content.text().equals(new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)), "SDK text must exactly match JAR bytes");
}
int[] hostUse = position(content.text(), "LowGfx.clear", "LowGfx.".length());
check(bridge.externalHover(context, uri, hostUse[0], hostUse[1], registry, consumer).markdown().contains("clear"), "SDK hover must work");
var host = bridge.navigation(context, uri, null, hostUse[0], hostUse[1], registry, consumer).locations().getFirst();
check(registry.read(consumer, host.uri()).text().split("\n")[host.startLine()].contains("clear"), "SDK to host definition range must match");
check(!bridge.externalSemanticTokens(context, uri, registry, consumer).tokens().isEmpty(), "SDK semantic highlighting must work");
int[] colorUse = position(content.text(), "color: Color", 7);
var core = bridge.navigation(context, uri, null, colorUse[0], colorUse[1], registry, consumer).locations().getFirst();
var coreContent = registry.read(consumer, core.uri());
check(coreContent.descriptor().readOnly() && coreContent.descriptor().name().replace('\\', '/').contains("core/color"), "SDK to core definition must resolve");
var coreResource = loader.getResource("game/stdlib/1/core/color/main.pbs");
check(coreResource != null && coreResource.getProtocol().equals("jar"), "Core must be read from a JAR URL");
try (var stream = coreResource.openStream()) {
check(coreContent.text().equals(new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)), "Core text must exactly match JAR bytes");
}
check(coreContent.text().split("\n")[core.startLine()].contains("Color"), "Core definition range must match");
registry.disconnect(consumer);
registry.connect(consumer, false);
check(registry.revalidate(consumer, uri, path -> bridge.currentSource(context, path)).text().equals(content.text()), "Bundled source must revalidate after reconnect");
}
try (var files = Files.walk(root)) {
check(files.filter(Files::isRegularFile).map(root::relativize).map(Path::toString).collect(java.util.stream.Collectors.toSet())
.equals(java.util.Set.of("prometeu.json", "src/main.pbs", "src/mod.barrel")), "Navigation must not extract bundled sources into the project");
}
System.out.println("Packaged external sources verified: JAR bytes, SDK/host/core navigation, hover, tokens, read-only, reconnect, no extraction");
}
private static int[] position(String text, String needle, int offset) {
int index = text.indexOf(needle);
check(index >= 0, "Missing source fragment: " + needle);
String prefix = text.substring(0, index + offset);
return new int[] {(int) prefix.chars().filter(c -> c == '\n').count(), prefix.length() - prefix.lastIndexOf('\n') - 1};
}
}
@@ -0,0 +1,46 @@
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 {
String log = runProbe();
assertTrue(log.contains("references; example compiled"), log);
assertTrue(log.contains("Packaged external sources verified"), log);
}
@Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception {
String log = runProbe("--catalog-only");
assertTrue(log.contains("Installed compiler/SDK catalog identity verified"), log);
}
private String runProbe(String... arguments) 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 command = new java.util.ArrayList<>(java.util.List.of(distribution.resolve("runtime/bin/java").toString(),
"-cp", jars + java.io.File.pathSeparator + probeClasses, InstalledKnowledgeProbe.class.getName()));
command.addAll(java.util.List.of(arguments));
var process = new ProcessBuilder(command)
.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);
return log;
} finally { if (process.isAlive()) process.destroyForcibly().waitFor(); }
}
}
@@ -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<FrontendReferenceProvider> 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<FrontendReferenceProvider> documentation() { return documentation; }
});
}
}
@@ -0,0 +1,79 @@
package p.studio.app.install;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.app.mcp.StudioAgentPreparation;
import p.studio.core.project.*;
import p.studio.api.project.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
class InstalledConnectorTest {
@TempDir Path temporary;
@Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception {
Path base = temporary.resolve("Application Support/Studio");
Path source = Path.of(System.getProperty("studio.test.distribution"));
Path first = ManagedStudioInstallation.install(source, base);
var mapper = new ObjectMapper();
var preparation = new StudioAgentPreparation(base, mapper);
var catalog = new ProjectCatalogService(temporary, mapper, new ProjectLocalStudioSetupStore(mapper), preparation);
var scaffold = catalog.createProject(new ProjectCreationRequest("Scaffold Game", temporary, "pbs", 1, ProjectTarget.Game, "src", 8, "/my/runtime"));
assertTrue(preparation.status(scaffold.rootPath()).ready());
Path existing = Files.createDirectory(temporary.resolve("Existing Project"));
Files.copy(scaffold.rootPath().resolve("prometeu.json"), existing.resolve("prometeu.json"));
Files.createDirectory(existing.resolve(".studio"));
Files.writeString(existing.resolve(".studio/setup.json"), "{\"runtimePath\":\"/preserved/runtime\",\"custom\":42}");
Files.createDirectory(existing.resolve(".codex"));
String custom = "# preserve\napproval_policy = \"on-request\"\n[mcp_servers.other]\ncommand = \"other\"\n";
Files.writeString(existing.resolve(".codex/config.toml"), custom);
assertTrue(preparation.prepare(existing).ready());
var config = existing.resolve(".codex/config.toml");
String stable = Files.readString(config); var modified = Files.getLastModifiedTime(config);
assertTrue(stable.startsWith(custom)); assertTrue(preparation.prepare(existing).ready());
assertEquals(stable, Files.readString(config)); assertEquals(modified, Files.getLastModifiedTime(config));
var setup = mapper.readTree(Files.readString(existing.resolve(".studio/setup.json")));
assertEquals(42, setup.path("custom").asInt()); assertEquals("/preserved/runtime", setup.path("runtimePath").asText());
assertFalse(Files.exists(existing.resolve(".studio/mcp/connection.json")));
runConnector(base, existing);
Path second = ManagedStudioInstallation.install(source, base);
assertNotEquals(first, second); assertTrue(Files.isDirectory(first));
assertEquals(second.toRealPath(), base.resolve("current").toRealPath());
assertEquals(stable, Files.readString(config)); runConnector(base, existing);
assertThrows(Exception.class, () -> ManagedStudioInstallation.install(existing, base));
assertEquals(second.toRealPath(), base.resolve("current").toRealPath()); runConnector(base, existing);
// Test fixture only: installed runtime/lib must load and start JavaFX, without checkout application classes.
String fixtures = Path.of(DesktopProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
var desktop = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*") + java.io.File.pathSeparator + fixtures,
DesktopProbe.class.getName()).redirectError(temporary.resolve("desktop.stderr").toFile()).start();
try { assertTrue(desktop.waitFor(20, TimeUnit.SECONDS)); assertEquals(0, desktop.exitValue(), Files.readString(temporary.resolve("desktop.stderr"))); }
finally { desktop.destroyForcibly(); }
}
void runConnector(Path base, Path root) throws Exception {
var process = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*").toString(),
"p.studio.app.StudioLauncher", "mcp", "--project", root.toRealPath().toString()).start();
try {
String input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"installed-test\",\"version\":\"1\"}}}\n";
process.getOutputStream().write(input.getBytes(java.nio.charset.StandardCharsets.UTF_8)); process.getOutputStream().close();
assertTrue(process.waitFor(15, TimeUnit.SECONDS)); assertEquals(0, process.exitValue());
assertEquals("prometeu-studio", new ObjectMapper().readTree(process.getInputStream()).path("result").path("serverInfo").path("name").asText());
} finally { process.destroyForcibly(); }
}
ProcessBuilder minimal(String... args) {
var builder = new ProcessBuilder(args).directory(temporary.toFile());
builder.environment().clear(); builder.environment().put("PATH", "/usr/bin:/bin"); builder.environment().put("HOME", System.getProperty("user.home"));
return builder;
}
public static class DesktopProbe {
public static void main(String[] args) {
javafx.application.Platform.startup(() -> {
try {
var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX")));
stage.show(); stage.close(); System.exit(0);
} catch (Throwable failure) { System.exit(2); }
});
}
}
}
@@ -0,0 +1,260 @@
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 {
String httpAuthorization;
@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<String, Object> parameters) {
return mapper.valueToTree(queries.query(root, task, operation, parameters));
}
Map<String, Object> at(int line, int character) {
return Map.of("uri", source.toUri().toString(), "position", Map.of("line", line, "character", character));
}
@Test void bundledSourcesAreReadableAcrossConnectionsAndOwnedByTheTask() throws Exception {
Files.writeString(source, "import { Gfx } from @sdk:gfx;\nfn main() -> void { Gfx.clear(0); }\n");
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn main() -> void;\n");
acquire();
final var definition = query("definition", at(1, 24)).path("result");
assertFalse(definition.isEmpty(), definition.toString());
final String uri = definition.get(0).path("uri").asText();
assertTrue(uri.startsWith("prometeu-source:"), uri);
final var content = query("readExternalSource", Map.of("uri", uri)).path("result");
assertTrue(content.path("descriptor").path("readOnly").asBoolean());
assertEquals("bundled", content.path("descriptor").path("origin").asText());
final String text = content.path("text").asText();
final int offset = text.indexOf("LowGfx.clear") + "LowGfx.".length();
assertTrue(offset > "LowGfx.".length());
final String prefix = text.substring(0, offset);
final var position = Map.of("line", (int) prefix.chars().filter(c -> c == '\n').count(),
"character", offset - prefix.lastIndexOf('\n') - 1);
final var request = Map.<String, Object>of("uri", uri, "position", position);
assertTrue(query("hover", request).path("result").toString().contains("clear"));
final var host = query("definition", request).path("result");
assertFalse(host.isEmpty());
assertTrue(query("readExternalSource", Map.of("uri", host.get(0).path("uri").asText()))
.path("result").path("text").asText().contains("declare host LowGfx"));
assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class,
() -> query("formatting", request)).failure().code());
session.automation().reclaim().toCompletableFuture().join();
acquire();
assertEquals(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, assertThrows(AutomationException.class,
() -> query("readExternalSource", Map.of("uri", uri))).failure().code());
}
@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.<String, Object>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.<String, Object>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 credential = server.credentials().prepare(root.toRealPath());
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
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<String> 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", httpAuthorization).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<String, Object> query(TaskIdentity task, String operation, Map<String, Object> 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());
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(booleans = {false, true})
void externalDependencyNavigationIsReadableButRefactoringIsReadOnly(boolean inWorkspace) throws Exception {
Path lib = Files.createDirectories(inWorkspace ? root.resolve(".workspace/repos/lib") : 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, "// á 😀\r\nfn answer() -> int { return helper(); }\r\nfn helper() -> int { return 42; }\r\n");
Files.writeString(module.resolve("mod.barrel"), "pub fn answer() -> int;\n");
manifest(root, "app", List.of(Map.of("path", inWorkspace ? ".workspace/repos/lib" : "../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());
assertTrue(locations.get(0).path("uri").asText().startsWith("prometeu-source:"));
assertEquals(Files.readString(declaration), query("readExternalSource", Map.of("uri", locations.get(0).path("uri").asText())).path("result").path("text").asText());
final String externalUri = locations.get(0).path("uri").asText();
assertEquals(1, locations.get(0).path("range").path("start").path("line").asInt());
final var nested = query("definition", Map.of("uri", externalUri, "position", Map.of("line", 1, "character", 28))).path("result");
assertFalse(nested.isEmpty(), nested.toString());
assertEquals(2, nested.get(0).path("range").path("start").path("line").asInt());
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());
final Path alias = Files.createSymbolicLink(root.resolve("src/dependency-alias.pbs"), declaration);
assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class,
() -> query("formatting", Map.of("uri", alias.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());
final String oldText = Files.readString(declaration);
Files.writeString(declaration, "// changed revision\n" + oldText);
assertThrows(AutomationException.class, () -> query("readExternalSource", Map.of("uri", externalUri)));
final var renewed = query("definition", at(1, 26)).path("result");
assertNotEquals(externalUri, renewed.get(0).path("uri").asText());
assertEquals(2, renewed.get(0).path("range").path("start").path("line").asInt());
}
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));
}
}
@@ -0,0 +1,201 @@
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;
@org.junit.jupiter.api.io.TempDir java.nio.file.Path root;
String authorization;
void authorize(java.nio.file.Path project) throws Exception {
var credential = server.credentials().prepare(project.toRealPath());
credential.activate(); authorization = "Bearer " + credential.secret();
}
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(); authorize(root);
}
@AfterEach void close() { server.close(); client.close(); }
HttpResponse<String> 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<String> post(String body) throws Exception {
return request("POST", server.connection().endpoint(), body.replace("/project", root.toRealPath().toString()), authorization, 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, authorization, 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 = authorization;
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 = authorization; server.close();
assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection);
server.start(); authorize(root); assertFalse(old.equals(authorization));
assertEquals(401, request("POST", server.connection().endpoint(), init(), old, 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(), authorization, 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 = authorization;
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 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(); authorize(root);
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")));
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());
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())) {
socket.setSoTimeout(3000);
String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + authorization
+ "\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", authorization)
.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", authorization)
.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", authorization)
.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());
}
@Test void projectCredentialsCannotCrossRootsOrReuseAnotherSession() throws Exception {
initialize();
var other = java.nio.file.Files.createDirectory(root.resolve("other")).toRealPath();
var credential = server.credentials().prepare(other); credential.activate();
var wire = "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\"}";
assertEquals(403, request("POST", server.connection().endpoint(), wire, "Bearer " + credential.secret(), null,
LocalMcpServer.PROTOCOL_VERSION, session).statusCode());
var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 5).put("method", "tools/call");
call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", other.toString());
var reply = mapper.readTree(post(call.toString()).body());
assertEquals("OUTSIDE_PROJECT_SCOPE", reply.path("result").path("structuredContent").path("error").path("code").asText());
assertEquals(0, calls.get());
server.credentials().authenticate(authorization).invalidate();
assertEquals(401, post(wire).statusCode());
}
}
@@ -0,0 +1,48 @@
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 preparationIsStableAndSeparateFromAuthority() 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 prepared = new AtomicInteger();
var canonical = root.toRealPath();
var guide = new McpConnectionGuide(server, projects, mapper, project -> {
assertEquals(canonical, project); prepared.incrementAndGet();
return new AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once.");
});
assertEquals(AgentConnectionGuide.State.UNAVAILABLE, guide.state(root));
var stable = guide.configuration(root);
assertTrue(guide.prepare(root).ready()); assertEquals(1, prepared.get());
assertEquals(ControlState.MANUAL, authority.snapshot().state());
assertNull(authority.snapshot().task());
server.start();
assertEquals(AgentConnectionGuide.State.WAITING_FOR_ACCESS, guide.state(root));
assertFalse(stable.contains("Bearer"));
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(stable.contains(instruction));
server.close(); server.start(); assertEquals(stable, guide.configuration(root));
assertThrows(AutomationException.class, () -> guide.configuration(root.resolve("unopened")));
authority.closeAsync().toCompletableFuture().join();
assertThrows(AutomationException.class, () -> guide.configuration(root));
registration.close();
}
}
}
@@ -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"));
}
}
@@ -0,0 +1,415 @@
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 {
String httpAuthorization;
@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(); runtime.shutdownGate.complete(null); }
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 (result.path("workerTerminated").asBoolean()) 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<Future<String>>();
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<String>(); 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 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();
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(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());
}
@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 credential = server.credentials().prepare(root.toRealPath());
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
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());
}
}
}
@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 credential = server.credentials().prepare(root.toRealPath());
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
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", httpAuthorization).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);
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<String> 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", httpAuthorization).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);
final CountDownLatch shutdownEntered = new CountDownLatch(1);
CompletableFuture<Void> shutdownGate = CompletableFuture.completedFuture(null);
TaskTools.HeadlessAction lastAction;
volatile boolean stopped, hold, cancelled;
volatile AutomationOutcome.Kind kind = AutomationOutcome.Kind.SUCCEEDED;
Map<String, Object> input;
FakeRuntime(String build) { this.build = build; }
public String sessionId() { return id; }
public void cancel() { cancelled = true; }
public CompletionStage<Void> shutdown() { shutdownEntered.countDown(); return shutdownGate.thenRun(() -> stopped = true); }
public 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<String, Object> 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<TrackedOperation.Progress> 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));
}
}
}
@@ -0,0 +1,115 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class ProjectConnectionPublisherTest {
@TempDir Path temporary;
final ObjectMapper mapper = new ObjectMapper();
LocalMcpServer server;
Path root;
@BeforeEach void start() throws Exception {
root = temporary.toRealPath();
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of())); server.start();
}
@AfterEach void stop() { server.close(); }
@Test void publishesPrivatelyOnlyActivatesExplicitlyAndCleansUpOwnedGeneration() throws Exception {
Files.writeString(root.resolve(".gitignore"), "# existing\n/build/\n");
var publisher = new ProjectConnectionPublisher(server, mapper);
var publication = publisher.prepare(root);
publication.publish();
var descriptor = ProjectConnectionFiles.read(root, mapper);
assertNull(server.credentials().authenticate("Bearer " + descriptor.credential()));
publication.activate();
assertEquals(root, server.credentials().authenticate("Bearer " + descriptor.credential()).root());
var file = root.resolve(ProjectConnectionFiles.RELATIVE);
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(file));
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(file.getParent()));
assertFalse(descriptor.toString().contains(descriptor.credential()));
assertThrows(Exception.class, () -> publisher.prepare(root));
publication.invalidate(); assertNull(server.credentials().authenticate("Bearer " + descriptor.credential()));
publication.close(); assertFalse(Files.exists(file)); assertTrue(Files.exists(file.resolveSibling("publication.lock")));
try (var next = publisher.prepare(root)) {
next.publish(); next.activate(); publication.close();
assertTrue(Files.exists(file));
assertNotEquals(descriptor.credential(), ProjectConnectionFiles.read(root, mapper).credential());
}
assertEquals("# existing\n/build/\n/.studio/mcp/\n", Files.readString(root.resolve(".gitignore")));
}
@Test void unsafePathsAndPermissionsNeverPublishSecrets() throws Exception {
Path destination = Files.createDirectory(root.resolve("outside"));
Files.createSymbolicLink(root.resolve(".studio"), destination);
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
assertFalse(Files.exists(destination.resolve("mcp")));
Files.delete(root.resolve(".studio"));
Path directory = ProjectConnectionFiles.directory(root);
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("rwxr-xr-x"));
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
}
@Test void malformedDescriptorsNeverSupplyAnArbitraryEndpoint() throws Exception {
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
publication.publish();
Path path = root.resolve(ProjectConnectionFiles.RELATIVE);
var valid = mapper.readTree(Files.readString(path));
for (String endpoint : java.util.List.of("https://example.com/mcp", "http://127.0.0.1:123/mcp?x=1", "http://localhost:123/mcp")) {
var bad = valid.deepCopy(); ((com.fasterxml.jackson.databind.node.ObjectNode) bad).put("endpoint", endpoint);
Files.writeString(path, bad.toString()); assertThrows(Exception.class, () -> ProjectConnectionFiles.read(root, mapper));
}
Files.writeString(path, valid.toString());
}
}
@Test void osLockRejectsAnotherJvmAndCrashAllowsRecoveryWithoutUnlinkingLock() throws Exception {
Process owner = ownerProcess();
try {
assertEquals("READY", java.util.concurrent.CompletableFuture.supplyAsync(() -> {
try { return owner.inputReader().readLine(); } catch (java.io.IOException failure) { throw new java.io.UncheckedIOException(failure); }
}).get(10, java.util.concurrent.TimeUnit.SECONDS));
var lock = root.resolve(".studio/mcp/publication.lock");
var inode = Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey();
Process conflict = ownerProcess();
try { assertTrue(conflict.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(2, conflict.exitValue()); }
finally { conflict.destroyForcibly(); }
owner.destroyForcibly(); assertTrue(owner.waitFor(10, java.util.concurrent.TimeUnit.SECONDS));
assertTrue(Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)));
try (var recovered = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
recovered.publish(); recovered.activate();
assertEquals(server.instanceId(), ProjectConnectionFiles.read(root, mapper).instanceId());
assertEquals(inode, Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey());
}
} finally { owner.destroyForcibly(); }
}
@Test void trackedDiscoveryTargetIsRejectedWithoutWritingCredentials() throws Exception {
var directory = ProjectConnectionFiles.directory(root);
var target = directory.resolve("connection.json"); Files.writeString(target, "tracked placeholder");
for (var command : java.util.List.of(java.util.List.of("git", "init", "-q"), java.util.List.of("git", "add", "-f", ProjectConnectionFiles.RELATIVE))) {
var process = new ProcessBuilder(command).directory(root.toFile()).redirectError(ProcessBuilder.Redirect.DISCARD).start();
assertTrue(process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(0, process.exitValue());
}
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
assertEquals("tracked placeholder", Files.readString(target));
assertFalse(Files.exists(directory.resolve("publication.lock")));
}
private Process ownerProcess() throws Exception {
return new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin/java").toString(), "-cp",
System.getProperty("studio.test.classpath"), Owner.class.getName(), root.toString())
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
}
public static class Owner {
public static void main(String[] args) throws Exception {
var mapper = new ObjectMapper();
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) {
server.start();
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(Path.of(args[0]))) {
publication.publish(); publication.activate(); System.out.println("READY"); System.out.flush(); System.in.read();
} catch (Exception conflict) { System.exit(2); }
}
}
}
}
@@ -0,0 +1,36 @@
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 java.nio.file.*;
import static org.junit.jupiter.api.Assertions.*;
class StudioAgentPreparationTest {
@TempDir Path temporary;
@Test void preservesUnrelatedTomlAndRejectsUserOwnedOrEditedEntry() throws Exception {
var preparation = new StudioAgentPreparation(temporary.resolve("Application Support/Studio"), new ObjectMapper());
String entry = preparation.entry(temporary.toRealPath());
String custom = "# keep exactly\napproval_policy = \"on-request\"\n[mcp_servers.custom]\ncommand = \"custom\"\n";
String merged = StudioAgentPreparation.merge(custom, entry);
assertTrue(merged.startsWith(custom)); assertEquals(merged, StudioAgentPreparation.merge(merged, entry));
assertFalse(merged.contains("credential")); assertFalse(merged.contains("connection.json"));
assertThrows(Exception.class, () -> StudioAgentPreparation.merge("[mcp_servers.prometeu_studio]\ncommand=\"mine\"\n", entry));
assertThrows(Exception.class, () -> StudioAgentPreparation.merge(merged.replace("startup_timeout_sec = 20", "startup_timeout_sec = 30"), entry));
String updated = StudioAgentPreparation.merge(merged, preparation.entry(temporary.resolve("another project")));
assertTrue(updated.startsWith(custom)); assertTrue(updated.contains("another project"));
}
@Test void absentInstallationReportsIncompleteAndDoesNotModifyClientConfig() throws Exception {
Files.writeString(temporary.resolve("prometeu.json"), "{}");
Files.createDirectory(temporary.resolve(".codex"));
Path config = temporary.resolve(".codex/config.toml"); Files.writeString(config, "# preserve\n");
var preparation = new StudioAgentPreparation(temporary.resolve("missing"), new ObjectMapper());
var result = preparation.prepare(temporary);
assertFalse(result.ready()); assertEquals("# preserve\n", Files.readString(config));
assertTrue(result.message().contains("Studio installation is missing"));
assertTrue(result.message().contains(":prometeu-app:stageStudioInstallation"));
assertTrue(result.message().contains("-Dstudio.installationRoot"));
assertFalse(Files.exists(temporary.resolve(".studio/mcp")));
assertEquals(result, preparation.status(temporary.toRealPath()));
}
}
@@ -0,0 +1,204 @@
package p.studio.app.mcp.stdio;
import com.fasterxml.jackson.databind.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.app.mcp.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class StudioMcpStdioTest {
@TempDir Path temporary;
final ObjectMapper mapper = new ObjectMapper();
Path root;
@BeforeEach void project() throws Exception { root = temporary.toRealPath(); Files.writeString(root.resolve("prometeu.json"), "{}"); }
LocalMcpServer server(AtomicInteger calls, String image) {
return new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of("studio_project_context", args -> {
calls.incrementAndGet();
return McpToolResult.successWithCapture(mapper, mapper.createObjectNode().put("projectRoot", args.path("projectRoot").asText()),
new p.studio.api.automation.CanonicalCapture("session", "build", 1, 1, 1, 1, 1, Base64.getDecoder().decode(image)), false);
})));
}
@Test void coldProcessDiscoversLaterGrantPreservesLargeImagesAndSurvivesRestart() throws Exception {
var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100);
try (var process = new Connector(root); var server = server(count, pixels)) {
process.initialize();
assertEquals(17, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
var waiting = process.call("studio_project_context", root);
assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText());
assertFalse(Files.exists(root.resolve(".studio")));
server.start();
var publisher = new ProjectConnectionPublisher(server, mapper);
try (var publication = publisher.prepare(root)) {
publication.publish(); publication.activate();
var result = process.call("studio_project_context", root);
assertFalse(result.path("isError").asBoolean(), result.path("structuredContent").toString());
assertEquals(pixels, result.path("content").get(1).path("data").asText());
assertEquals(root.toString(), result.path("structuredContent").path("value").path("projectRoot").asText());
Path other = Files.createDirectory(root.resolve("other"));
assertEquals("OUTSIDE_PROJECT_SCOPE", process.call("studio_project_context", other).path("structuredContent").path("error").path("code").asText());
assertEquals(1, count.get());
}
server.close(); server.start();
assertEquals("WAITING_FOR_ACCESS", process.call("studio_project_context", root).path("structuredContent").path("error").path("code").asText());
try (var fresh = publisher.prepare(root)) {
fresh.publish(); fresh.activate();
assertFalse(process.call("studio_project_context", root).path("isError").asBoolean());
assertEquals(2, count.get());
}
}
}
@Test void invalidArgumentsAndMalformedLinesDoNotLaunchDesktopOrBreakCorrelation() throws Exception {
try (var connector = new Connector(root)) {
connector.send("{bad json}");
assertEquals(-32700, connector.read().path("error").path("code").asInt());
connector.initialize();
assertEquals(-32601, connector.request("no-method", mapper.createObjectNode()).path("error").path("code").asInt());
assertTrue(connector.request("ping", mapper.createObjectNode()).has("result"));
}
var process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", "relative")
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
assertTrue(process.waitFor(10, TimeUnit.SECONDS)); assertNotEquals(0, process.exitValue());
assertEquals(0, process.getInputStream().readAllBytes().length);
}
@Test void lostBuildResponseIsNotReplayedAndReceiptCanBeLookedUpAfterReconnect() throws Exception {
var builds = new AtomicInteger(); var mapper = this.mapper;
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
"studio_build_start", args -> { builds.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")); },
"studio_operation_get", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")));
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
var transport = java.net.http.HttpClient.newHttpClient()) {
server.start();
var proxy = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
var dropped = new java.util.concurrent.atomic.AtomicBoolean();
proxy.createContext("/mcp", exchange -> {
try (exchange) {
var bytes = exchange.getRequestBody().readAllBytes();
var incoming = mapper.readTree(bytes);
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint());
for (String header : List.of("Authorization", "Content-Type", "Accept", "Mcp-Session-Id", "MCP-Protocol-Version")) {
String value = exchange.getRequestHeaders().getFirst(header); if (value != null) request.header(header, value);
}
var response = transport.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofByteArray(bytes)).build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray());
if (incoming.path("params").path("name").asText().equals("studio_build_start") && dropped.compareAndSet(false, true)) {
exchange.sendResponseHeaders(200, 100); return; // Committed tool, intentionally incomplete transport response.
}
response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> exchange.getResponseHeaders().set("Mcp-Session-Id", value));
exchange.sendResponseHeaders(response.statusCode(), response.body().length == 0 ? -1 : response.body().length);
exchange.getResponseBody().write(response.body());
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
});
proxy.start();
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root);
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
publication.publish(); publication.activate();
var path = root.resolve(ProjectConnectionFiles.RELATIVE);
var descriptor = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(Files.readString(path));
descriptor.put("endpoint", "http://127.0.0.1:" + proxy.getAddress().getPort() + "/mcp"); Files.writeString(path, descriptor.toString());
var args = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "task").put("clientRequestId", "intent-1");
var unknown = connection.call("studio_build_start", args);
assertEquals("OUTCOME_UNKNOWN", unknown.path("structuredContent").path("error").path("code").asText());
assertEquals("intent-1", unknown.path("structuredContent").path("error").path("clientRequestId").asText());
connection.probe(); assertEquals(1, builds.get());
var recovered = connection.call("studio_operation_get", args);
assertEquals("op-1", recovered.path("structuredContent").path("value").path("operationId").asText());
assertEquals(1, builds.get());
} finally { proxy.stop(0); }
}
}
@Test void restartedInstanceCannotClaimRecoveryOfOldTaskReceipts() throws Exception {
var calls = new AtomicInteger();
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
"studio_control_acquire", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("taskId", UUID.randomUUID().toString())),
"studio_operation_get", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "fresh")); });
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
server.start(); var publisher = new ProjectConnectionPublisher(server, mapper);
String task;
try (var publication = publisher.prepare(root)) {
publication.publish(); publication.activate();
task = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString()))
.path("structuredContent").path("value").path("taskId").asText();
}
server.close(); server.start();
try (var publication = publisher.prepare(root)) {
publication.publish(); publication.activate();
var old = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", task).put("clientRequestId", "old");
assertEquals("OUTCOME_UNKNOWN", connection.call("studio_operation_get", old).path("structuredContent").path("error").path("code").asText());
assertEquals(0, calls.get());
String fresh = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString()))
.path("structuredContent").path("value").path("taskId").asText();
old.put("taskId", fresh);
assertFalse(connection.call("studio_operation_get", old).path("isError").asBoolean()); assertEquals(1, calls.get());
}
}
}
@Test void staleIdentityAndCatalogMismatchAreRejectedBeforeToolDispatch() throws Exception {
var calls = new AtomicInteger();
try (var server = server(calls, "AAAA")) {
server.start();
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
publication.publish(); publication.activate();
Path path = root.resolve(ProjectConnectionFiles.RELATIVE);
String valid = Files.readString(path);
try {
for (String field : List.of("instanceId", "catalogFingerprint")) {
var invalid = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(valid); invalid.put(field, "outdated");
Files.writeString(path, invalid.toString());
try (var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()));
assertEquals(field.equals("instanceId") ? "STALE_CONNECTION" : "VERSION_INCOMPATIBLE",
result.path("structuredContent").path("error").path("code").asText());
}
}
assertEquals(0, calls.get());
} finally { Files.writeString(path, valid); }
}
}
}
static String java() { return Path.of(System.getProperty("java.home"), "bin/java").toString(); }
static String classpath() { return System.getProperty("studio.test.classpath"); }
final class Connector implements AutoCloseable {
final Process process;
final BufferedReader reader;
final BufferedWriter writer;
final ExecutorService reads = Executors.newSingleThreadExecutor();
final Path errors;
int sequence;
Connector(Path project) throws Exception {
errors = Files.createTempFile(temporary, "stdio-", ".stderr");
process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", project.toString())
.directory(temporary.toFile()).redirectError(errors.toFile()).start();
reader = process.inputReader(); writer = process.outputWriter();
}
void send(String value) throws Exception { writer.write(value); writer.newLine(); writer.flush(); }
JsonNode read() throws Exception {
String line = reads.submit(reader::readLine).get(15, TimeUnit.SECONDS);
assertNotNull(line, Files.readString(errors)); return mapper.readTree(line);
}
JsonNode request(String method, JsonNode params) throws Exception {
var value = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", ++sequence).put("method", method); value.set("params", params);
send(value.toString()); var response = read(); assertEquals(sequence, response.path("id").asInt()); return response;
}
void initialize() throws Exception {
var params = mapper.createObjectNode().put("protocolVersion", "2025-06-18"); params.putObject("capabilities"); params.putObject("clientInfo").put("name", "process-test").put("version", "1");
assertEquals("2025-06-18", request("initialize", params).path("result").path("protocolVersion").asText());
send("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}");
}
JsonNode call(String name, Path root) throws Exception {
var params = mapper.createObjectNode().put("name", name); params.putObject("arguments").put("projectRoot", root.toString());
return request("tools/call", params).path("result");
}
public void close() throws Exception {
try { writer.close(); assertTrue(process.waitFor(10, TimeUnit.SECONDS), "EOF must terminate the connector"); assertEquals(0, process.exitValue(), Files.readString(errors)); }
finally { process.destroyForcibly(); reads.shutdownNow(); }
}
}
}
@@ -12,6 +12,39 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
final class ExecutorOperationExecutorTest { 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 @Test
void completesWithTypedResultAndTerminalSnapshot() throws Exception { void completesWithTypedResultAndTerminalSnapshot() throws Exception {
final var executor = Executors.newSingleThreadExecutor(); final var executor = Executors.newSingleThreadExecutor();
@@ -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<ProcessHandle> 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(); }
}
}
@@ -0,0 +1,90 @@
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();
// 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);
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(limits(mode)));
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" -> {
if (mode.startsWith("load-fault-")) {
var resource = "/runtime/fault-" + mode.substring("load-fault-".length()) + ".json";
var fault = MAPPER.readTree(HeadlessFixture.class.getResourceAsStream(resource));
var error = MAPPER.createObjectNode().put("code", "boot_failed").put("message", "Runtime rejected cartridge");
error.putObject("details").set("fault", fault);
emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", "fixture").put("requestId", id).set("error", error));
} else 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(); }
}
@@ -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=<extracted runtime installation>");
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<TrackedOperation.Progress>();
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());
}
}
}
@@ -0,0 +1,465 @@
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<ProcessHandle> owned = new HashSet<>();
ConfigurableApplicationContext app;
ProjectSession project;
LocalMcpServer server;
HttpClient client;
String connection, task, build, session;
String authorization = "Bearer unavailable";
Path installation, source;
DevWorkspace dev;
Stage stage;
I18nService locale;
@BeforeAll static void toolkit() throws Exception {
var ready = new CompletableFuture<Void>();
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<Void>();
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=<runtime distribution>");
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();
});
}
void connect() throws Exception {
authorization = "Bearer " + p.studio.app.mcp.ProjectConnectionFiles.read(root, mapper).credential();
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");
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");
}
void grant() throws Exception {
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (project.automation().snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(10);
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
connect();
}
void acquire() throws Exception {
grant();
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", authorization).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<Void>(); var refreshGate = new CompletableFuture<Void>();
var refreshed = new java.util.concurrent.atomic.AtomicReference<String>();
var handoff = project.automation().registerDocuments(new DocumentHandoff() {
public CompletionStage<Boolean> hasUnsavedChanges() { return CompletableFuture.completedFuture(false); }
public CompletionStage<Void> saveAll() { throw new AssertionError("Do not write old buffers"); }
public CompletionStage<Void> 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(401, post(request("ping")).statusCode());
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 {
grant();
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
assertEquals(401, post(request("ping")).statusCode());
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(401, post(request("ping")).statusCode());
project = app.getBean(ProjectSessionFactory.class).open(project.projectReference());
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
assertEquals(401, post(request("ping")).statusCode());
}
@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(401, post(request("ping")).statusCode());
grant();
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("LowPad"), "Consult installed SDK source through the indexed read-only reference");
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 { Pad, Button, Touch } from @sdk:input;")
.replace("x = x + 1;", "if (Pad.down(Button.Right)) { 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<JsonNode> 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<JsonNode> 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<JsonNode>();
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<JsonNode> expected, List<JsonNode> 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<String> post(JsonNode body) throws Exception {
var request = HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15))
.header("Authorization", authorization).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());
}
}
@@ -0,0 +1,111 @@
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;
final List<HeadlessProcessSession> 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(), HeadlessFixture.limits(mode), "build"); sessions.add(session); return session;
}
@AfterEach void cleanup() { sessions.forEach(session -> session.abort("test cleanup")); }
@Test void productionLoadDiagnosticsSurviveBootFailureAndMcpSerialization() throws Exception {
var mapper = new ObjectMapper();
for (String fixture : List.of("resource", "invalid-role", "retired-opcode", "native", "native-abi", "unknown-native")) {
var session = start("load-fault-" + fixture);
var failure = assertThrows(AutomationException.class, () -> session.initializeAndBoot(root)).failure();
var fault = mapper.readTree(getClass().getResourceAsStream("/runtime/fault-" + fixture + ".json"));
var error = mapper.valueToTree(failure.runtimeError());
assertEquals(fault, error.path("details").path("fault"));
assertTrue(error.path("details").path("fault").path("pc").isNull());
var wire = p.studio.app.mcp.McpToolResult.failure(mapper, failure).wire();
assertEquals(fault, wire.path("structuredContent").path("error").path("runtimeError").path("details").path("fault"));
assertThrows(UnsupportedOperationException.class, () -> failure.runtimeError().put("code", "changed"));
}
}
@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<TrackedOperation.Progress>();
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<TrackedOperation.Progress>();
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(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(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());
}
@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());
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 {
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());
}
}
@@ -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<ProcessHandle> ownedProcesses = new HashSet<>();
@BeforeEach void open() throws Exception {
root = root.toRealPath();
String installation = System.getProperty("studio.test.runtimeInstall", "");
assertFalse(installation.isBlank(), "Supply -PstudioRuntimeInstall=<runtime distribution>");
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();
}
}
@@ -0,0 +1,24 @@
{
"initError": {
"code": "registry_load_failed",
"load": {
"code": "LOAD_INVALID_REGISTRY",
"function": 0,
"id_domain": null,
"limit": null,
"member": null,
"offset": 136,
"pc": null,
"reason": "LifecycleRole",
"record": 0,
"referenced_id": null,
"requested": null,
"resource": null,
"section": 1
},
"message": "RegistryLoadFailed(LoadFailure { code: InvalidRegistry, reason: LifecycleRole, section: Some(1), offset: Some(136), record: Some(0), member: None, id_domain: None, referenced_id: None, function: Some(0), pc: None, resource: None, requested: None, limit: None })"
},
"kind": "vm_init",
"pc": null,
"summary": "Conformance fixture"
}
@@ -0,0 +1,19 @@
{
"initError": {
"binding": {
"declared_arg_slots": 1,
"declared_ret_slots": 1,
"expected_arg_slots": 0,
"expected_ret_slots": 1,
"module": "system",
"name": "has_cart",
"reason": "abi_mismatch",
"version": 1
},
"code": "loader_patch_failed",
"message": "LoaderPatchFailed(ResolveFailed(AbiMismatch { module: \"system\", name: \"has_cart\", version: 1, declared_arg_slots: 1, declared_ret_slots: 1, expected_arg_slots: 0, expected_ret_slots: 1 }))"
},
"kind": "vm_init",
"pc": null,
"summary": "Conformance fixture"
}
@@ -0,0 +1,17 @@
{
"initError": {
"binding": {
"module": "system",
"name": "has_cart",
"provided": 0,
"reason": "missing_capability",
"required": 1,
"version": 1
},
"code": "loader_patch_failed",
"message": "LoaderPatchFailed(ResolveFailed(MissingCapability { required: 1, provided: 0, module: \"system\", name: \"has_cart\", version: 1 }))"
},
"kind": "vm_init",
"pc": null,
"summary": "Conformance fixture"
}
@@ -0,0 +1,24 @@
{
"initError": {
"code": "registry_load_failed",
"load": {
"code": "LOAD_RESOURCE_LIMIT",
"function": null,
"id_domain": null,
"limit": 0,
"member": null,
"offset": null,
"pc": null,
"reason": "Limit",
"record": null,
"referenced_id": null,
"requested": 32,
"resource": "Work",
"section": null
},
"message": "RegistryLoadFailed(LoadFailure { code: ResourceLimit, reason: Limit, section: None, offset: None, record: None, member: None, id_domain: None, referenced_id: None, function: None, pc: None, resource: Some(Work), requested: Some(32), limit: Some(0) })"
},
"kind": "vm_init",
"pc": null,
"summary": "Conformance fixture"
}
@@ -0,0 +1,24 @@
{
"initError": {
"code": "registry_load_failed",
"load": {
"code": "LOAD_INVALID_CODE",
"function": 0,
"id_domain": null,
"limit": null,
"member": null,
"offset": null,
"pc": 0,
"reason": "Truncated",
"record": null,
"referenced_id": null,
"requested": null,
"resource": null,
"section": 2
},
"message": "RegistryLoadFailed(LoadFailure { code: InvalidCode, reason: Truncated, section: Some(2), offset: None, record: None, member: None, id_domain: None, referenced_id: None, function: Some(0), pc: Some(0), resource: None, requested: None, limit: None })"
},
"kind": "vm_init",
"pc": null,
"summary": "Conformance fixture"
}
@@ -0,0 +1,15 @@
{
"initError": {
"binding": {
"module": "system",
"name": "missing",
"reason": "unknown_syscall",
"version": 1
},
"code": "loader_patch_failed",
"message": "LoaderPatchFailed(ResolveFailed(UnknownSyscall { module: \"system\", name: \"missing\", version: 1 }))"
},
"kind": "vm_init",
"pc": null,
"summary": "Conformance fixture"
}
@@ -9,6 +9,13 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
@AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class) @AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class)
class StudioBoundaryArchTest { 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..", "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 @ArchTest
static final ArchRule staticContainerCannotReturn = noClasses() static final ArchRule staticContainerCannotReturn = noClasses()
.that().resideInAnyPackage("p.studio..") .that().resideInAnyPackage("p.studio..")
@@ -1,3 +1,5 @@
import java.security.MessageDigest
plugins { plugins {
id("gradle.java-library-conventions") id("gradle.java-library-conventions")
} }
@@ -8,3 +10,56 @@ dependencies {
implementation(project(":prometeu-compiler:prometeu-frontend-api")) implementation(project(":prometeu-compiler:prometeu-frontend-api"))
implementation(project(":prometeu-compiler:prometeu-compiler-core")) 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 pbsAlignmentSpecs = rootProject.layout.projectDirectory.dir("docs/compiler/pbs/specs")
val pbsResources = layout.projectDirectory.dir("src/main/resources")
val generatePbsKnowledge by tasks.registering(Sync::class) {
from(pbsSpecs) { include("*.md"); into("pbs-knowledge/specs") }
from(pbsAlignmentSpecs) { 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<Map<String, Any?>>()
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()!!.toList() + (pbsAlignmentSpecs.asFile.listFiles()?.toList() ?: emptyList())).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) }
tasks.named<ProcessResources>("processResources") {
from(rootProject.layout.projectDirectory.dir("docs/vm-arch")) {
include("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv", "runtime-catalog.properties")
into("runtime-catalog/pbs-sdk")
}
}
@@ -32,6 +32,7 @@ import p.studio.compiler.services.FrontendDocumentLink;
import p.studio.compiler.services.FrontendFoldingRange; import p.studio.compiler.services.FrontendFoldingRange;
import p.studio.compiler.services.FrontendSelectionRange; import p.studio.compiler.services.FrontendSelectionRange;
import p.studio.compiler.services.FrontendDefinitionLocation; import p.studio.compiler.services.FrontendDefinitionLocation;
import p.studio.compiler.services.FrontendSourceDocument;
import p.studio.compiler.services.FrontendDocumentRequest; import p.studio.compiler.services.FrontendDocumentRequest;
import p.studio.compiler.services.FrontendDocumentSymbol; import p.studio.compiler.services.FrontendDocumentSymbol;
import p.studio.compiler.services.FrontendRenameEdit; import p.studio.compiler.services.FrontendRenameEdit;
@@ -63,6 +64,38 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
public final class PBSFrontendLanguageService implements FrontendLanguageService { public final class PBSFrontendLanguageService implements FrontendLanguageService {
@Override
public boolean supportsExternalSources() { return true; }
@Override
public Optional<FrontendSourceDocument> sourceDocument(
final FrontendDocumentRequest request,
final FrontendEditorialContext context,
final Path path) {
if (!(context.projectSurface() instanceof PbsSemanticReadSurface surface)
|| !(context.sourceFiles() instanceof FileTableReader files)) return Optional.empty();
FrontendSourceDocument projectSource = null;
for (final var entry : surface.astByFile().entrySet()) {
final var handle = files.get(entry.getKey());
if (handle == null || !handle.getCanonPath().toAbsolutePath().normalize().equals(path.toAbsolutePath().normalize())) continue;
final var text = handle.readUtf8();
if (text.isEmpty()) return Optional.empty();
final boolean bundled = surface.sourceKindByFile().get(entry.getKey()) == SourceKind.SDK_INTERFACE;
final Path owner = surface.ownerRootByFile().get(entry.getKey());
final boolean external = bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize());
final var source = new FrontendSourceDocument(path, text.orElseThrow(),
bundled ? "bundled" : external ? "dependency" : "project",
handle.getRelativePath().toString(), "pbs", external,
new FrontendEditorialContext(entry.getValue(),
surface.supplementalTopDeclsByFile().getOrDefault(entry.getKey(), ReadOnlyList.empty()),
context.semanticContext(), files, surface));
// A dependency may physically overlap a project source root. External
// ownership wins even if another file-table entry treats it as local.
if (external) return Optional.of(source);
projectSource = source;
}
return Optional.ofNullable(projectSource);
}
private final PbsEditorialSupportService editorialSupportService; private final PbsEditorialSupportService editorialSupportService;
private final PBSSemanticTokenProvider semanticTokenProvider; private final PBSSemanticTokenProvider semanticTokenProvider;
@@ -257,7 +290,12 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
typedSupplementalTopDecls, typedSupplementalTopDecls,
feSurfaceContext, feSurfaceContext,
offset)) { offset)) {
toFrontendLocation(location, fileTable).ifPresent(locations::add); final var handle = fileTable.get(location.span().getFileId());
if (handle != null) {
sourceDocument(request, editorialContext, handle.getCanonPath()).ifPresent(source ->
locations.add(new FrontendDefinitionLocation(source.path(),
toOffset(location.span().getStart()), toOffset(location.span().getEnd()), source)));
}
} }
return List.copyOf(locations); return List.copyOf(locations);
} }
@@ -401,14 +439,16 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
} }
final LinkedHashMap<String, FrontendRenameEdit> edits = new LinkedHashMap<>(); final LinkedHashMap<String, FrontendRenameEdit> edits = new LinkedHashMap<>();
for (final PbsEditorialLocation site : planned.sites()) { for (final PbsEditorialLocation site : planned.sites()) {
toFrontendLocation(site, fileTable).ifPresent(location -> final var mapped = toFrontendLocation(site, fileTable);
edits.putIfAbsent( if (mapped.isEmpty()) return FrontendRenameResult.refused("rename requires a non-editable source");
final var location = mapped.orElseThrow();
edits.putIfAbsent(
frontendLocationKey(location), frontendLocationKey(location),
new FrontendRenameEdit( new FrontendRenameEdit(
location.path(), location.path(),
location.startOffset(), location.startOffset(),
location.endOffset(), location.endOffset(),
newName))); newName));
} }
if (edits.isEmpty()) { if (edits.isEmpty()) {
return FrontendRenameResult.refused("not renameable"); return FrontendRenameResult.refused("not renameable");
@@ -11,6 +11,8 @@ import java.util.Optional;
public final class PBSFrontendProvider implements FrontendProvider { public final class PBSFrontendProvider implements FrontendProvider {
private final FrontendPhaseService compiler; private final FrontendPhaseService compiler;
private final PBSFrontendLanguageService languageService; private final PBSFrontendLanguageService languageService;
private final p.studio.compiler.services.FrontendReferenceProvider documentation =
new p.studio.compiler.pbs.documentation.PbsDocumentation();
public PBSFrontendProvider() { public PBSFrontendProvider() {
this(new PBSFrontendPhaseService(), new PBSFrontendLanguageService()); this(new PBSFrontendPhaseService(), new PBSFrontendLanguageService());
@@ -41,4 +43,9 @@ public final class PBSFrontendProvider implements FrontendProvider {
public Optional<FrontendLanguageService> languageService() { public Optional<FrontendLanguageService> languageService() {
return Optional.of(languageService); return Optional.of(languageService);
} }
@Override
public Optional<p.studio.compiler.services.FrontendReferenceProvider> documentation() {
return Optional.of(documentation);
}
} }
@@ -25,7 +25,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProvider { public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProvider {
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "float", "bool", "string", "i32", "i64", "f32", "f64"); private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "long", "float", "bool", "string", "i32", "i64", "f32", "f64");
private static final int DEFAULT_STDLIB_VERSION = 1; private static final int DEFAULT_STDLIB_VERSION = 1;
private static final AppMode DEFAULT_TARGET = AppMode.Game; private static final AppMode DEFAULT_TARGET = AppMode.Game;
private static final ResourceStdlibEnvironmentResolver STDLIB_RESOLVER = new ResourceStdlibEnvironmentResolver(); private static final ResourceStdlibEnvironmentResolver STDLIB_RESOLVER = new ResourceStdlibEnvironmentResolver();
@@ -234,7 +234,7 @@ public final class PbsFrontendCompiler {
effectiveModulePool, effectiveModulePool,
ReadOnlyList.wrap(callableSignatures), ReadOnlyList.wrap(callableSignatures),
executableLowering.intrinsicPool(), executableLowering.intrinsicPool(),
lifecycleDeclaration); lifecycleDeclaration, executableLowering.registry());
} }
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) { public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {

Some files were not shown because too many files have changed in this diff Show More