Compare commits

..
Author SHA1 Message Date
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
bquarkz a0a5050d5e complete Studio core and JavaFX boundary migration
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 64.01% (20482/31999) * Branch Coverage: 54.22% (8240/15196) * Lines of Code: 31999 * Cyclomatic Complexity: 13164 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 715
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
2026-09-25 11:28:18 +01:00
bquarkz 10f1b3f87c clean up 2026-09-24 07:41:17 +01:00
bquarkz 7011209675 Merge pull request 'dev/pbs-lsp-remaining-editor-surface' (#31) from dev/pbs-lsp-remaining-editor-surface into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.92% (20214/31624) * Branch Coverage: 54.09% (8188/15137) * Lines of Code: 31624 * Cyclomatic Complexity: 13003 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 701
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #31
2026-09-22 09:00:21 +00:00
bquarkz 274ce28e8d clean up and fixes
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.92% (20214/31624) * Branch Coverage: 54.09% (8188/15137) * Lines of Code: 31624 * Cyclomatic Complexity: 13003 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 701
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
2026-09-22 09:53:21 +01:00
bquarkz 1fcecdb04d implements PLN-0137 (7/7) call-hierarchy
Call hierarchy walks CallExpr nodes for functions and methods. It does
not use the references index. A cursor that is not on a callable is
empty, and type hierarchy stays unadvertised.

Housekeep DSC-0066 with LSN-0074.
2026-09-22 09:20:28 +01:00
bquarkz e456bb8d7a implements PLN-0137 (6/7) module-ref-completion
Completion inside a ModuleRef lists project and stdlib modules the
current resolver can already name. Completion after a dot stays the
existing member list. Items remain eager, resolveProvider stays false,
and there is no snippet or ranking score.
2026-09-22 09:13:40 +01:00
bquarkz 202c785f94 implements PLN-0137 (5/7) semantic-token-overlay
Keep the lexical token provider as the baseline. When hover resolution
names a symbol and an existing semantic key matches it, replace the
weaker identifier token. A failed resolution, a broken file, or a
symbol without an existing key keeps the provider token. No new
semantic key is added.
2026-09-22 09:09:43 +01:00
bquarkz 7629a73e0a implements PLN-0137 (4/7) document-formatting
Advertise full-document formatting only. The formatter reprints the
token stream and changes indentation by four spaces where brace or
parenthesis nesting changes. Doc text-block interiors stay as written,
comments stay on their current line, and declarations are not reordered.
Range formatting and on-type formatting stay off.
2026-09-22 08:50:18 +01:00
bquarkz ce2e3e4cd3 implements PLN-0137 (3/7) folding-and-selection-ranges
Advertise folding and selection only when the frontend supports them.
Folding uses recovered spans for the listed declarations, their bodies,
parameter lists, and Doc text blocks. A brace, parenthesis, or text
block the tree does not cover still folds, including an unmatched
opener through the end of the text. Selection grows outward from the
identifier to the argument or parameter list, the block, and the
declaration.
2026-09-22 08:45:31 +01:00
bquarkz 3320f222bb implements PLN-0137 (2/7) document-links
Advertise document links only when the frontend supports them.
A link covers the ModuleRef span when module assembly already
bound that module to a regular file. Virtual stdlib and unresolved
modules produce no link.
2026-09-22 08:34:13 +01:00
bquarkz 099857b636 implements PLN-0137 (1/7) diagnostic-source
Lock DSC-0066 on Q1-A and Q2-A. Retire AGD-0048 through AGD-0056
into AGD-0069, DEC-0058, and PLN-0137.

Published editor diagnostics use the bound frontend language id as
source. For PBS that is pbs. The stable compiler code stays in code
and is not copied into source. Related locations, phase, and repair
payload stay unpublished.
2026-09-22 08:11:06 +01:00
bquarkz 20adc196d9 Merge pull request 'implements PLN-0136' (#30) from dev/pbs-lsp-code-actions-and-quick-fixes into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.75% (19407/30442) * Branch Coverage: 54.17% (7740/14289) * Lines of Code: 30442 * Cyclomatic Complexity: 12365 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 685
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #30
2026-09-22 06:51:07 +00:00
bquarkz ae891262e1 implements PLN-0136
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.75% (19407/30442) * Branch Coverage: 54.17% (7740/14289) * Lines of Code: 30442 * Cyclomatic Complexity: 12365 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 685
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add PBS quick fixes as frontend-owned repairs transported by the LSP.
Duplicate reserved attributes are deleted at the extra span. Interface
InitAllowed attributes with arguments become [InitAllowed]. The server
matches Diagnostic.code plus range, does not parse messages, and returns
an empty list when the capability or the fix is absent.

Housekeep DSC-0044 with LSN-0073.
2026-09-22 07:43:05 +01:00
bquarkz 6f45f4f205 Merge pull request 'implements PLN-0135' (#29) from dev/pbs-lsp-rename-symbol into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.56% (19159/30145) * Branch Coverage: 54.14% (7612/14060) * Lines of Code: 30145 * Cyclomatic Complexity: 12214 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 678
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #29
2026-09-22 05:54:40 +00:00
bquarkz 65d2d40310 implements PLN-0135
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.56% (19159/30145) * Branch Coverage: 54.14% (7612/14060) * Lines of Code: 30145 * Cyclomatic Complexity: 12214 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 678
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add PBS rename as a validated WorkspaceEdit of physical identifier
sites on FrontendLanguageService. Identity is definition; locals and
params rename from their name span. Refuse aliases, virtual stdlib,
builtins, error labels, keywords, and collisions. Advertise
renameProvider with prepareProvider; refused cursors are LSP errors,
not empty success.

Housekeep DSC-0043 with LSN-0072.
2026-09-22 06:40:18 +01:00
bquarkz fa21a029ae Merge pull request 'implements PLN-0134' (#28) from dev/pbs-lsp-workspace-symbols into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.37% (18783/29640) * Branch Coverage: 53.99% (7369/13648) * Lines of Code: 29640 * Cyclomatic Complexity: 11938 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 674
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #28
2026-09-21 16:27:42 +00:00
bquarkz 12e2a4edcc implements PLN-0134
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.37% (18783/29640) * Branch Coverage: 53.99% (7369/13648) * Lines of Code: 29640 * Cyclomatic Complexity: 11938 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 674
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add PBS workspace symbols as a physical flatten of the outline
named-declaration set on FrontendLanguageService. Regular files
only; virtual stdlib, barrels, imports, locals, and compile-only
frontends stay empty. Advertise workspaceSymbolProvider with flat
SymbolInformation. workspace/symbol does not require an open
document.

Housekeep DSC-0042 with LSN-0071.
2026-09-21 17:18:00 +01:00
649 changed files with 26776 additions and 8742 deletions
+5
View File
@@ -24,3 +24,8 @@ build
**/.studio/**
.DS_Store
# Discussion workflow state is local; only consolidated lessons are versioned.
discussion/*
!discussion/lessons/
!discussion/lessons/**
+124 -7
View File
@@ -8,8 +8,10 @@ This repository packages the Studio shell together with the embedded services it
The root project is a monorepo with these main areas:
- `prometeu-app`: JavaFX application entry point (`p.studio.App`).
- `prometeu-studio`: Studio UI, workspaces, project session lifecycle, play/stop flow, and debugger-facing surfaces.
- `prometeu-app`: Spring Boot non-web composition, concrete adapters, packaging, and JavaFX entry point (`p.studio.app.StudioLauncher`).
- `prometeu-studio-api`: toolkit-neutral Studio contracts and operation surfaces.
- `prometeu-studio-core`: JavaFX-free project, session, assets, shipper, runtime, and execution services.
- `prometeu-studio-ui-javafx`: the current human-facing JavaFX adapter.
- `prometeu-packer`: embedded packer APIs and implementation used by Studio.
- `prometeu-compiler`: compiler core, build pipeline, frontend APIs, and the PBS frontend.
- `prometeu-infra`: shared infrastructure used across modules.
@@ -19,14 +21,127 @@ The root project is a monorepo with these main areas:
## Current Product Shape
The Studio shell currently organizes the product around three workspaces:
The Studio shell currently organizes the product around four workspaces:
- Assets
- Debug
- DEV (external-agent authorization and observation)
- Shipper
At runtime, the app boots an embedded packer, restores project-local Studio state, and opens the Studio launcher window. Project creation currently scaffolds a Prometeu workspace with `prometeu.json`, `src/`, `assets/`, `build/`, `cartridge/`, `.workspace/`, and local Studio metadata.
## External Coding Agents (MCP)
Open a project and select **DEV → Copy MCP configuration**. The copied JSON is a
provider-neutral connection descriptor: use its `url` and `headers.Authorization`
in your external client's Streamable HTTP MCP setup, and provide its `projectRoot`
and instructions to the agent. Adapt the configuration syntax to your client;
there is no embedded chat or provider-specific setup wizard.
Keep the descriptor/token private and out of versioned files and logs. The endpoint
is local to this computer. After restarting Studio, copy it again and update the
client: both the port and token are ephemeral. Copying or connecting does not
authorize edits or start a task.
1. Connect, discover tools, read project context and applicable language/SDK references.
2. In DEV, grant control (save all first if prompted). Active Debug prevents granting.
3. The agent acquires a task, edits saved project files using its own tools, and
validates through LSP/build. SDK and external libraries are consultable, read-only.
4. Poll operations by operationId or clientRequestId. Recover a lost start receipt
by lookup; never retry frame advancement blindly with a new ID.
5. The agent explicitly releases control. To interrupt, use DEV's reclaim button
and stop the external client separately: Studio cannot prevent its direct file writes.
The current production tools cover context, references, task control, LSP,
build/pack, 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 |
| --- | --- |
| Connection rejected after Studio restarts | Copy DEV's configuration again: the token and OS-assigned endpoint are session-local. Do not publish the token. |
| Acquisition rejected or project busy | Grant control in DEV first; stop manual Debug before granting. Query an existing operation instead of starting another; serialize headless calls. |
| `RUNTIME_UNAVAILABLE` or handshake incompatibility | Check the project's configured runtime installation and its packaged headless command. Studio does not download a substitute. |
| `NO_FRAME_AVAILABLE` | Advance at least one frame before requesting a capture. |
| Advance/page limit rejected | Respect advertised limits and use reference pagination. Runtime's default maximum is 600 frames per advance; requests are not silently clamped. |
| Unknown language or missing reference | Inspect project context and the declared manifest language; use only advertised capabilities/reference IDs. PBS is a creation default, not an unknown-language fallback. |
| Returning control reports cleanup failure | Stop the external client's direct editing separately, then retry DEV reclaim after owned-process cleanup. Do not bypass the lock or restore stale editor buffers. |
Language and SDK references are bundled locally; reading them does not require a
compiler checkout or network download. SDK/external-library changes remain outside
the game-authoring task, even when a reference exposes a limitation.
The real headless process adapter and task-service composition can be verified
using an extracted runtime distribution:
```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:** definition lookup for the bundled SDK's `Input.pad()`
currently returns no location. Project-source navigation and indexed SDK reference
reads work. Investigate SDK symbol resolution separately; an empty definition
result is not evidence of missing runtime support or permission to edit the SDK.
- **Build tooling:** the validation environment's JDK 25 triggers Kotlin's target-24
fallback and Java/Kotlin target compatibility warnings in `buildSrc`. The targeted
regression passes, but the toolchain/target alignment needs separate review.
Cross-platform desktop coverage remains a validation boundary, not a confirmed
product defect. Desktop acceptance so far covers macOS ARM64 and Codex CLI only.
The first real Codex CLI acceptance run exercised editing, LSP, build/pack, input,
1,110 frames, native MCP images and explicit release. The developer confirmed the
DEV result and successfully ran the edited game using manual Debug Play afterward.
Additional follow-ups from that run: clearer errors for oversized
reference pages, guidance for sequential headless queries after `BUSY`, and easier
discovery of framebuffer dimensions. Capture before the first completed frame
correctly returns `NO_FRAME_AVAILABLE`; it is not a runtime defect. Noninteractive
clients must also provide an approval path for MCP work calls; the acceptance used
Codex's approval review with a project-scoped workspace-write sandbox.
The completed baseline's architecture, acceptance evidence and post-implementation
follow-ups are consolidated in [LSN-0076](discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md).
## Requirements
- JDK 21 or newer recommended for local development
@@ -64,9 +179,11 @@ Generate the aggregated coverage report:
If you are new to the codebase, this order is usually the fastest path:
1. Start at `prometeu-app` to see application bootstrap.
2. Read `prometeu-studio` for the shell, workspaces, and user-facing flows.
3. Read `prometeu-packer` for asset and packaging boundaries.
4. Read `prometeu-compiler` when you need compiler or PBS language behavior.
2. Read `prometeu-studio-api` and `prometeu-studio-core` for Studio contracts and application services.
3. Read `prometeu-studio-ui-javafx` for the current shell, workspaces, and human-facing flows.
4. Read `prometeu-app` for Spring composition and provider gateways.
5. Read `prometeu-packer` for asset and packaging boundaries.
6. Read `prometeu-compiler` when you need compiler or PBS language behavior.
## Specs And Architecture
@@ -76,4 +193,4 @@ Important reference surfaces:
- `docs/specs/packer/`: packer specifications
- `docs/vm-arch/`: VM and ISA architecture references
These documents are the long-term normative source for behavior and contracts. When code and docs diverge, fix the divergence explicitly instead of relying on tribal knowledge.
These documents are the long-term normative source for behavior and contracts. When code and docs diverge, fix the divergence explicitly instead of relying on tribal knowledge.
@@ -1,14 +0,0 @@
{"type":"meta","next_id":{"DSC":14,"AGD":15,"DEC":10,"PLN":19,"LSN":28,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"open","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[{"id":"AGD-0013","file":"AGD-0013-studio-editor-write-wave-supported-non-frontend-files.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31"},{"id":"AGD-0014","file":"AGD-0014-studio-editor-frontend-edit-rights.md","status":"open","created_at":"2026-03-31","updated_at":"2026-03-31"}],"decisions":[],"plans":[],"lessons":[]}
@@ -1,14 +0,0 @@
{"type":"meta","next_id":{"DSC":14,"AGD":15,"DEC":12,"PLN":19,"LSN":28,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"open","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[{"id":"AGD-0013","file":"AGD-0013-studio-editor-write-wave-supported-non-frontend-files.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31"},{"id":"AGD-0014","file":"AGD-0014-studio-editor-frontend-edit-rights.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31"}],"decisions":[{"id":"DEC-0010","file":"DEC-0010-studio-controlled-non-frontend-editor-write-wave.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31","ref_agenda":"AGD-0013"},{"id":"DEC-0011","file":"DEC-0011-studio-frontend-read-only-minimum-lsp-phase.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31","ref_agenda":"AGD-0014"}],"plans":[],"lessons":[]}
@@ -1,15 +0,0 @@
{"type":"meta","next_id":{"DSC":14,"AGD":15,"DEC":13,"PLN":29,"LSN":28,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"open","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[{"id":"AGD-0013","file":"AGD-0013-studio-editor-write-wave-supported-non-frontend-files.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31"},{"id":"AGD-0014","file":"AGD-0014-studio-editor-frontend-edit-rights.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31"}],"decisions":[{"id":"DEC-0010","file":"DEC-0010-studio-controlled-non-frontend-editor-write-wave.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31","ref_agenda":"AGD-0013"},{"id":"DEC-0011","file":"DEC-0011-studio-frontend-read-only-minimum-lsp-phase.md","status":"accepted","created_at":"2026-03-31","updated_at":"2026-03-31","ref_agenda":"AGD-0014"}],"plans":[{"id":"PLN-0019","file":"PLN-0019-propagate-dec-0010-into-studio-and-vfs-specs.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0010"]},{"id":"PLN-0020","file":"PLN-0020-build-dec-0010-vfs-access-policy-and-save-core.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0010"]},{"id":"PLN-0021","file":"PLN-0021-integrate-dec-0010-editor-write-ui-and-workflow.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0010"]},{"id":"PLN-0022","file":"PLN-0022-propagate-dec-0011-into-studio-vfs-and-lsp-specs.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0011"]},{"id":"PLN-0023","file":"PLN-0023-scaffold-flat-packed-prometeu-lsp-api-and-session-seams.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0011"]},{"id":"PLN-0024","file":"PLN-0024-implement-read-only-fe-diagnostics-symbols-and-definition.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0011"]},{"id":"PLN-0025","file":"PLN-0025-implement-fe-semantic-highlight-consumption.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31","ref_decisions":["DEC-0011"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0014","status":"open","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[{"id":"AGD-0015","file":"AGD-0015-studio-frontend-owned-semantic-editor-presentation.md","status":"accepted","created_at":"2026-04-02","updated_at":"2026-04-02"}],"decisions":[{"id":"DEC-0012","file":"DEC-0012-frontend-owned-semantic-editor-presentation.md","status":"accepted","created_at":"2026-04-02","updated_at":"2026-04-02","ref_agenda":"AGD-0015"}],"plans":[{"id":"PLN-0026","file":"PLN-0026-propagate-dec-0012-into-studio-and-frontend-specs.md","status":"review","created_at":"2026-04-02","updated_at":"2026-04-02","ref_decisions":["DEC-0012"]},{"id":"PLN-0027","file":"PLN-0027-add-frontend-semantic-presentation-contract-and-lsp-descriptor.md","status":"review","created_at":"2026-04-02","updated_at":"2026-04-02","ref_decisions":["DEC-0012"]},{"id":"PLN-0028","file":"PLN-0028-consume-frontend-owned-semantic-presentation-in-studio.md","status":"review","created_at":"2026-04-02","updated_at":"2026-04-02","ref_decisions":["DEC-0012"]}],"lessons":[]}
@@ -1,15 +0,0 @@
{"type":"meta","next_id":{"DSC":15,"AGD":16,"DEC":13,"PLN":29,"LSN":29,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"open","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[{"id":"AGD-0015","file":"AGD-0015-studio-frontend-owned-semantic-editor-presentation.md","status":"accepted","created_at":"2026-04-02","updated_at":"2026-04-02"}],"decisions":[{"id":"DEC-0012","file":"DEC-0012-frontend-owned-semantic-editor-presentation.md","status":"accepted","created_at":"2026-04-02","updated_at":"2026-04-02","ref_agenda":"AGD-0015"}],"plans":[{"id":"PLN-0026","file":"PLN-0026-propagate-dec-0012-into-studio-and-frontend-specs.md","status":"review","created_at":"2026-04-02","updated_at":"2026-04-02","ref_decisions":["DEC-0012"]},{"id":"PLN-0027","file":"PLN-0027-add-frontend-semantic-presentation-contract-and-lsp-descriptor.md","status":"review","created_at":"2026-04-02","updated_at":"2026-04-02","ref_decisions":["DEC-0012"]},{"id":"PLN-0028","file":"PLN-0028-consume-frontend-owned-semantic-presentation-in-studio.md","status":"review","created_at":"2026-04-02","updated_at":"2026-04-02","ref_decisions":["DEC-0012"]}],"lessons":[]}
@@ -1,19 +0,0 @@
{"type":"meta","next_id":{"DSC":19,"AGD":20,"DEC":17,"PLN":38,"LSN":31,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"open","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[{"id":"AGD-0017","file":"AGD-0017-studio-editor-scope-guides-and-brace-anchoring.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"decisions":[{"id":"DEC-0014","file":"DEC-0014-studio-editor-active-scope-and-structural-anchors.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"plans":[{"id":"PLN-0030","file":"PLN-0030-studio-active-container-and-active-scope-gutter-wave-1.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"},{"id":"PLN-0031","file":"PLN-0031-studio-structural-anchor-semantic-surface-specification.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"},{"id":"PLN-0032","file":"PLN-0032-frontend-structural-anchor-payloads-and-anchor-aware-tests.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}],"lessons":[]}
{"type":"discussion","id":"DSC-0017","status":"open","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[{"id":"AGD-0018","file":"AGD-0018-studio-editor-inline-type-hints-for-let-bindings.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"decisions":[{"id":"DEC-0015","file":"DEC-0015-studio-editor-inline-type-hints-contract-and-rendering-model.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03","ref_agenda":"AGD-0018"}],"plans":[{"id":"PLN-0033","file":"PLN-0033-inline-hint-spec-and-contract-propagation.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0034","file":"PLN-0034-lsp-inline-hint-transport-contract.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0035","file":"PLN-0035-pbs-inline-type-hint-payload-production.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0036","file":"PLN-0036-studio-inline-hint-rendering-and-rollout.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0018","status":"open","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[{"id":"AGD-0019","file":"AGD-0019-studio-project-open-state-under-dot-studio.md","status":"accepted","created_at":"2026-04-04","updated_at":"2026-04-04"}],"decisions":[{"id":"DEC-0016","file":"DEC-0016-project-local-studio-state-under-dot-studio.md","status":"accepted","created_at":"2026-04-04","updated_at":"2026-04-04","ref_agenda":"AGD-0019"}],"plans":[{"id":"PLN-0037","file":"PLN-0037-project-local-studio-state-store-and-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04","ref_decisions":["DEC-0016"]}],"lessons":[]}
@@ -1,20 +0,0 @@
{"type":"meta","next_id":{"DSC":20,"AGD":21,"DEC":18,"PLN":39,"LSN":32,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"open","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[{"id":"AGD-0017","file":"AGD-0017-studio-editor-scope-guides-and-brace-anchoring.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"decisions":[{"id":"DEC-0014","file":"DEC-0014-studio-editor-active-scope-and-structural-anchors.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"plans":[{"id":"PLN-0030","file":"PLN-0030-studio-active-container-and-active-scope-gutter-wave-1.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"},{"id":"PLN-0031","file":"PLN-0031-studio-structural-anchor-semantic-surface-specification.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"},{"id":"PLN-0032","file":"PLN-0032-frontend-structural-anchor-payloads-and-anchor-aware-tests.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}],"lessons":[]}
{"type":"discussion","id":"DSC-0017","status":"open","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[{"id":"AGD-0018","file":"AGD-0018-studio-editor-inline-type-hints-for-let-bindings.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"decisions":[{"id":"DEC-0015","file":"DEC-0015-studio-editor-inline-type-hints-contract-and-rendering-model.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03","ref_agenda":"AGD-0018"}],"plans":[{"id":"PLN-0033","file":"PLN-0033-inline-hint-spec-and-contract-propagation.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0034","file":"PLN-0034-lsp-inline-hint-transport-contract.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0035","file":"PLN-0035-pbs-inline-type-hint-payload-production.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0036","file":"PLN-0036-studio-inline-hint-rendering-and-rollout.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0018","status":"done","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0031","file":"discussion/lessons/DSC-0018-studio-project-local-studio-state-under-dot-studio/LSN-0031-project-local-studio-state-and-lifecycle-safe-layout-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0019","status":"open","ticket":"studio-project-local-setup-separate-from-main-studio-state","title":"Separate project-local setup from the main Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","setup","boundary"],"agendas":[{"id":"AGD-0020","file":"AGD-0020-project-local-setup-separate-from-main-studio-state.md","status":"accepted","created_at":"2026-04-04","updated_at":"2026-04-04"}],"decisions":[{"id":"DEC-0017","file":"DEC-0017-project-local-setup-separate-from-session-state.md","status":"accepted","created_at":"2026-04-04","updated_at":"2026-04-04","ref_agenda":"AGD-0020"}],"plans":[{"id":"PLN-0038","file":"PLN-0038-separate-project-local-setup-from-session-state.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04","ref_decisions":["DEC-0017"]}],"lessons":[]}
@@ -1,22 +0,0 @@
{"type":"meta","next_id":{"DSC":22,"AGD":23,"DEC":20,"PLN":41,"LSN":34,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"open","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["studio","debugger","workspace","integration","shell"],"agendas":[{"id":"AGD-0009","file":"AGD-0009-studio-debugger-workspace-integration.md","status":"open","created_at":"2026-03-30","updated_at":"2026-03-30"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"open","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[{"id":"AGD-0017","file":"AGD-0017-studio-editor-scope-guides-and-brace-anchoring.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"decisions":[{"id":"DEC-0014","file":"DEC-0014-studio-editor-active-scope-and-structural-anchors.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"plans":[{"id":"PLN-0030","file":"PLN-0030-studio-active-container-and-active-scope-gutter-wave-1.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"},{"id":"PLN-0031","file":"PLN-0031-studio-structural-anchor-semantic-surface-specification.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"},{"id":"PLN-0032","file":"PLN-0032-frontend-structural-anchor-payloads-and-anchor-aware-tests.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}],"lessons":[]}
{"type":"discussion","id":"DSC-0017","status":"open","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[{"id":"AGD-0018","file":"AGD-0018-studio-editor-inline-type-hints-for-let-bindings.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03"}],"decisions":[{"id":"DEC-0015","file":"DEC-0015-studio-editor-inline-type-hints-contract-and-rendering-model.md","status":"accepted","created_at":"2026-04-03","updated_at":"2026-04-03","ref_agenda":"AGD-0018"}],"plans":[{"id":"PLN-0033","file":"PLN-0033-inline-hint-spec-and-contract-propagation.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0034","file":"PLN-0034-lsp-inline-hint-transport-contract.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0035","file":"PLN-0035-pbs-inline-type-hint-payload-production.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]},{"id":"PLN-0036","file":"PLN-0036-studio-inline-hint-rendering-and-rollout.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03","ref_decisions":["DEC-0015"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0018","status":"done","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0031","file":"discussion/lessons/DSC-0018-studio-project-local-studio-state-under-dot-studio/LSN-0031-project-local-studio-state-and-lifecycle-safe-layout-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0019","status":"done","ticket":"studio-project-local-setup-separate-from-main-studio-state","title":"Separate project-local setup from the main Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","setup","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0032","file":"discussion/lessons/DSC-0019-studio-project-local-setup-separate-from-main-studio-state/LSN-0032-separate-project-config-from-session-restoration-state.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0020","status":"done","ticket":"studio-editor-indentation-policy-and-project-setup","title":"Indentation Policy, Status-Bar Semantics, and Project-Local Editor Setup","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","editor","indentation","tabs","setup","dot-studio","configuration","ux"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0033","file":"discussion/lessons/DSC-0020-studio-editor-indentation-policy-and-project-setup/LSN-0033-setup-owned-indentation-policy-and-project-bootstrap-defaults.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0021","status":"open","ticket":"studio-frontend-editor-write-and-save-wave","title":"Enable Frontend Editing and Save in the Studio Code Editor","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","editor","frontend","write","save","vfs","lsp","pbs","access-policy"],"agendas":[{"id":"AGD-0022","file":"AGD-0022-studio-frontend-editor-write-and-save-wave.md","status":"accepted","created_at":"2026-04-04","updated_at":"2026-04-04"}],"decisions":[{"id":"DEC-0019","file":"DEC-0019-studio-frontend-editor-write-and-save-wave.md","status":"accepted","created_at":"2026-04-04","updated_at":"2026-04-04","ref_agenda":"AGD-0022"}],"plans":[{"id":"PLN-0040","file":"PLN-0040-studio-frontend-editor-write-and-save-wave.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04","ref_decisions":["DEC-0019"]}],"lessons":[]}
@@ -1,31 +0,0 @@
{"type":"meta","next_id":{"DSC":31,"AGD":34,"DEC":31,"PLN":62,"LSN":47,"CLSN":1}}
{"type":"discussion","id":"DSC-0030","status":"done","ticket":"studio-scene-pack-runtime-binary-contract","title":"Studio scene pack contract for runtime SCENE binary payload","created_at":"2026-04-24","updated_at":"2026-05-01","tags":["studio","packer","runtime","scene","asset-pack","binary-format","tiled"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0030-studio-scene-pack-runtime-binary-contract/LSN-0046-canonical-scene-owns-editorial-truth-while-pack-stays-request-driven.md","status":"done","created_at":"2026-05-01","updated_at":"2026-05-01"}]}
{"type":"discussion","id":"DSC-0029","status":"done","ticket":"studio-frame-composer-syscall-and-sprite-alignment","title":"Studio Alignment with Runtime FrameComposer Syscalls and Sprite Composition","created_at":"2026-04-18","updated_at":"2026-04-18","tags":["studio","compiler","pbs","stdlib","runtime-alignment","abi","syscall","frame-composer","sprites"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0041","file":"discussion/lessons/DSC-0029-studio-frame-composer-syscall-and-sprite-alignment/LSN-0041-composer-must-own-public-sprite-composition.md","status":"done","created_at":"2026-04-18","updated_at":"2026-04-18"}]}
{"type":"discussion","id":"DSC-0028","status":"done","ticket":"studio-tiled-parser-assets-scene-asset-type","title":"Tiled Parser and Scene Asset-Type Ownership in Assets Workspace","created_at":"2026-04-15","updated_at":"2026-04-23","tags":["studio","assets","scene","tiled","parser","asset-type"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0028-studio-tiled-parser-assets-scene-asset-type/LSN-0045-asset-owned-scene-bank-and-tiled-xml-workflow.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0027","status":"abandoned","ticket":"studio-scene-workspace","title":"Scene Workspace for SCENE Authoring","created_at":"2026-04-14","updated_at":"2026-04-15","tags":["studio","workspace","scene","tilemap","asset","runtime-alignment"],"agendas":[{"id":"AGD-0029","file":"AGD-0029-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted agenda and its downstream work."}],"decisions":[{"id":"DEC-0026","file":"DEC-0026-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_agenda":"AGD-0029","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted decision and stop using it as normative guidance."}],"plans":[{"id":"PLN-0049","file":"PLN-0049-scene-workspace-spec-and-boundary-propagation.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0050","file":"PLN-0050-scene-workspace-shell-and-project-state-foundations.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0051","file":"PLN-0051-scene-artifact-and-assets-handoff-contract.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0052","file":"PLN-0052-scene-workspace-wave-1-tilemap-editor.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."}],"lessons":[]}
{"type":"discussion","id":"DSC-0026","status":"done","ticket":"glyph-bank-naming-alignment-with-runtime","title":"Glyph Bank Naming Alignment with Runtime DEC-0006","created_at":"2026-04-10","updated_at":"2026-04-10","tags":["packer","studio","naming","asset-contract","runtime-alignment","glyph-bank"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0040","file":"discussion/lessons/DSC-0026-glyph-bank-naming-alignment-with-runtime/LSN-0040-glyph-bank-artifact-naming-alignment.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0025","status":"done","ticket":"packer-pipeline-metadata-ownership","title":"Pipeline Metadata Ownership and Runtime Contract","created_at":"2026-04-09","updated_at":"2026-04-10","tags":["packer","metadata","runtime-contract","tooling","studio"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0039","file":"discussion/lessons/DSC-0025-packer-pipeline-metadata-ownership/LSN-0039-runtime-header-boundary-and-tooling-owned-pipeline-metadata.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0024","status":"done","ticket":"jacoco-reports-consolidation","title":"JaCoCo Reports Consolidation in Gradle","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["infra","gradle","jacoco","coverage","jenkins"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0038","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0038-jacoco-reports-consolidation.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"},{"id":"LSN-0044","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0044-jenkins-jacoco-alignment.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-04-23","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0002-palette-management-in-studio/LSN-0042-schema-driven-palette-authoring-and-local-metadata-events.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"abandoned","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-04-24","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"abandoned","created_at":"2026-03-26","updated_at":"2026-04-24","_override_reason":"Explicit user request on 2026-04-24 to abandon AGD-0004 because the agenda is no longer valid."}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-04-07","tags":["studio","debugger","workspace","integration","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"done","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0034","file":"discussion/lessons/DSC-0016-studio-editor-scope-guides-and-brace-anchoring/LSN-0034-active-scope-gutter-and-frontend-owned-structural-anchors.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0017","status":"done","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0035","file":"discussion/lessons/DSC-0017-studio-editor-inline-type-hints-for-let-bindings/LSN-0035-frontend-owned-inline-hints-with-decorative-inline-rendering.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0018","status":"done","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0031","file":"discussion/lessons/DSC-0018-studio-project-local-studio-state-under-dot-studio/LSN-0031-project-local-studio-state-and-lifecycle-safe-layout-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0019","status":"done","ticket":"studio-project-local-setup-separate-from-main-studio-state","title":"Separate project-local setup from the main Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","setup","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0032","file":"discussion/lessons/DSC-0019-studio-project-local-setup-separate-from-main-studio-state/LSN-0032-separate-project-config-from-session-restoration-state.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0020","status":"done","ticket":"studio-editor-indentation-policy-and-project-setup","title":"Indentation Policy, Status-Bar Semantics, and Project-Local Editor Setup","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","editor","indentation","tabs","setup","dot-studio","configuration","ux"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0033","file":"discussion/lessons/DSC-0020-studio-editor-indentation-policy-and-project-setup/LSN-0033-setup-owned-indentation-policy-and-project-bootstrap-defaults.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0021","status":"done","ticket":"studio-frontend-editor-write-and-save-wave","title":"Enable Frontend Editing and Save in the Studio Code Editor","created_at":"2026-04-04","updated_at":"2026-04-06","tags":["studio","editor","frontend","write","save","vfs","lsp","pbs","access-policy"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0021-studio-frontend-editor-write-and-save-wave/LSN-0036-vfs-owned-frontend-edit-and-save-wave.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0022","status":"done","ticket":"studio-play-stop-cartridge-flow","title":"Wire the Studio Play/Stop button to shipper phase 1 cartridge preparation and runtime execution","created_at":"2026-04-06","updated_at":"2026-04-07","tags":["studio","play-stop","shipper","runtime","cartridge","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0043","file":"discussion/lessons/DSC-0022-studio-play-stop-and-debugger-integration/LSN-0043-studio-play-stop-and-debugger-integration.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0023","status":"done","ticket":"gradle-version-catalog-migration","title":"Move dependency version management to Version Catalog (TOML)","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["gradle","buildSrc","dependency-management","version-catalog"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0023-gradle-version-catalog-migration/LSN-0037-gradle-version-catalog-adoption.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
@@ -1,35 +0,0 @@
{"type":"meta","next_id":{"DSC":35,"AGD":38,"DEC":35,"PLN":75,"LSN":47,"CLSN":1}}
{"type":"discussion","id":"DSC-0034","status":"in_progress","ticket":"frontend-semantic-host-projection-flexibility","title":"Frontend semantic vocabulary flexibility and declarative host projection","created_at":"2026-05-06","updated_at":"2026-05-06","tags":["compiler","compiler-general","frontend","semantics","vscode","host-projection","lsp"],"agendas":[{"id":"AGD-0037","file":"AGD-0037-frontend-semantic-host-projection-flexibility.md","status":"accepted","created_at":"2026-05-06","updated_at":"2026-05-06"}],"decisions":[{"id":"DEC-0034","file":"DEC-0034-frontend-semantic-host-projection-flexibility.md","status":"accepted","created_at":"2026-05-06","updated_at":"2026-05-06","ref_agenda":"AGD-0037"}],"plans":[{"id":"PLN-0072","file":"PLN-0072-frontend-semantic-host-projection-contract.md","status":"done","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0034"]},{"id":"PLN-0073","file":"PLN-0073-lsp-semantic-host-projection-transport.md","status":"done","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0034"]},{"id":"PLN-0074","file":"PLN-0074-vscode-semantic-host-projection-adapter.md","status":"done","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0034"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0033","status":"in_progress","ticket":"frontend-visual-theme-spec-and-css-retirement","title":"Frontend visual theme spec and retirement of host-consumed semantic CSS","created_at":"2026-05-06","updated_at":"2026-05-06","tags":["compiler","compiler-general","frontend","presentation","theming","studio","vscode","lsp","pbs"],"agendas":[{"id":"AGD-0036","file":"AGD-0036-frontend-visual-theme-spec-and-css-retirement.md","status":"accepted","created_at":"2026-05-06","updated_at":"2026-05-06"}],"decisions":[{"id":"DEC-0033","file":"DEC-0033-frontend-visual-theme-spec-and-css-retirement.md","status":"accepted","created_at":"2026-05-06","updated_at":"2026-05-06","ref_agenda":"AGD-0036"}],"plans":[{"id":"PLN-0068","file":"PLN-0068-frontend-visual-contract-and-pbs-migration.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]},{"id":"PLN-0069","file":"PLN-0069-lsp-visual-theme-transport-and-selection.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]},{"id":"PLN-0070","file":"PLN-0070-studio-visual-theme-adapter-and-css-retirement.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]},{"id":"PLN-0071","file":"PLN-0071-vscode-dynamic-theme-translation-adapter.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0032","status":"in_progress","ticket":"studio-new-lsp-api-and-v1-boundary","title":"Novo boundary entre lsp-api, lsp-v1 e a extensao VS Code","created_at":"2026-05-05","updated_at":"2026-05-05","tags":["studio","lsp","vscode","protocol","api","boundary"],"agendas":[{"id":"AGD-0035","file":"AGD-0035-studio-new-lsp-api-and-v1-boundary.md","status":"accepted","created_at":"2026-05-05","updated_at":"2026-05-05"}],"decisions":[{"id":"DEC-0032","file":"DEC-0032-studio-new-lsp-api-and-v1-boundary.md","status":"accepted","created_at":"2026-05-05","updated_at":"2026-05-05","ref_agenda":"AGD-0035"}],"plans":[{"id":"PLN-0065","file":"PLN-0065-lsp-boundary-and-module-scaffolding.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0032"]},{"id":"PLN-0066","file":"PLN-0066-project-scoped-lsp-server-lifecycle-in-studio.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0032"]},{"id":"PLN-0067","file":"PLN-0067-compiler-backed-dumb-lsp-server-baseline.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0032"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0031","status":"in_progress","ticket":"studio-editor-workspace-cleanup","title":"Limpeza completa do Workspace Editor do Studio e remoção dos acoplamentos legados","created_at":"2026-05-05","updated_at":"2026-05-05","tags":["studio","editor","cleanup","vfs","lsp","migration"],"agendas":[{"id":"AGD-0034","file":"AGD-0034-vscode-editor-migration-feasibility.md","status":"accepted","created_at":"2026-05-05","updated_at":"2026-05-05"}],"decisions":[{"id":"DEC-0031","file":"DEC-0031-studio-editor-workspace-cleanup.md","status":"in_progress","created_at":"2026-05-05","updated_at":"2026-05-05","ref_agenda":"AGD-0034"}],"plans":[{"id":"PLN-0062","file":"PLN-0062-shell-session-and-state-cleanup-after-editor-removal.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0031"]},{"id":"PLN-0063","file":"PLN-0063-legacy-lsp-and-vfs-module-removal-with-runtime-preservation.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0031"]},{"id":"PLN-0064","file":"PLN-0064-normative-test-and-lesson-cleanup-for-editor-stack-removal.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0031"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0030","status":"done","ticket":"studio-scene-pack-runtime-binary-contract","title":"Studio scene pack contract for runtime SCENE binary payload","created_at":"2026-04-24","updated_at":"2026-05-01","tags":["studio","packer","runtime","scene","asset-pack","binary-format","tiled"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0030-studio-scene-pack-runtime-binary-contract/LSN-0046-canonical-scene-owns-editorial-truth-while-pack-stays-request-driven.md","status":"done","created_at":"2026-05-01","updated_at":"2026-05-01"}]}
{"type":"discussion","id":"DSC-0029","status":"done","ticket":"studio-frame-composer-syscall-and-sprite-alignment","title":"Studio Alignment with Runtime FrameComposer Syscalls and Sprite Composition","created_at":"2026-04-18","updated_at":"2026-04-18","tags":["studio","compiler","pbs","stdlib","runtime-alignment","abi","syscall","frame-composer","sprites"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0041","file":"discussion/lessons/DSC-0029-studio-frame-composer-syscall-and-sprite-alignment/LSN-0041-composer-must-own-public-sprite-composition.md","status":"done","created_at":"2026-04-18","updated_at":"2026-04-18"}]}
{"type":"discussion","id":"DSC-0028","status":"done","ticket":"studio-tiled-parser-assets-scene-asset-type","title":"Tiled Parser and Scene Asset-Type Ownership in Assets Workspace","created_at":"2026-04-15","updated_at":"2026-04-23","tags":["studio","assets","scene","tiled","parser","asset-type"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0028-studio-tiled-parser-assets-scene-asset-type/LSN-0045-asset-owned-scene-bank-and-tiled-xml-workflow.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0027","status":"abandoned","ticket":"studio-scene-workspace","title":"Scene Workspace for SCENE Authoring","created_at":"2026-04-14","updated_at":"2026-04-15","tags":["studio","workspace","scene","tilemap","asset","runtime-alignment"],"agendas":[{"id":"AGD-0029","file":"AGD-0029-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted agenda and its downstream work."}],"decisions":[{"id":"DEC-0026","file":"DEC-0026-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_agenda":"AGD-0029","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted decision and stop using it as normative guidance."}],"plans":[{"id":"PLN-0049","file":"PLN-0049-scene-workspace-spec-and-boundary-propagation.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0050","file":"PLN-0050-scene-workspace-shell-and-project-state-foundations.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0051","file":"PLN-0051-scene-artifact-and-assets-handoff-contract.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0052","file":"PLN-0052-scene-workspace-wave-1-tilemap-editor.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."}],"lessons":[]}
{"type":"discussion","id":"DSC-0026","status":"done","ticket":"glyph-bank-naming-alignment-with-runtime","title":"Glyph Bank Naming Alignment with Runtime DEC-0006","created_at":"2026-04-10","updated_at":"2026-04-10","tags":["packer","studio","naming","asset-contract","runtime-alignment","glyph-bank"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0040","file":"discussion/lessons/DSC-0026-glyph-bank-naming-alignment-with-runtime/LSN-0040-glyph-bank-artifact-naming-alignment.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0025","status":"done","ticket":"packer-pipeline-metadata-ownership","title":"Pipeline Metadata Ownership and Runtime Contract","created_at":"2026-04-09","updated_at":"2026-04-10","tags":["packer","metadata","runtime-contract","tooling","studio"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0039","file":"discussion/lessons/DSC-0025-packer-pipeline-metadata-ownership/LSN-0039-runtime-header-boundary-and-tooling-owned-pipeline-metadata.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0024","status":"done","ticket":"jacoco-reports-consolidation","title":"JaCoCo Reports Consolidation in Gradle","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["infra","gradle","jacoco","coverage","jenkins"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0038","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0038-jacoco-reports-consolidation.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"},{"id":"LSN-0044","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0044-jenkins-jacoco-alignment.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-04-23","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0002-palette-management-in-studio/LSN-0042-schema-driven-palette-authoring-and-local-metadata-events.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"abandoned","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-04-24","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"abandoned","created_at":"2026-03-26","updated_at":"2026-04-24","_override_reason":"Explicit user request on 2026-04-24 to abandon AGD-0004 because the agenda is no longer valid."}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-04-07","tags":["studio","debugger","workspace","integration","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"done","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0034","file":"discussion/lessons/DSC-0016-studio-editor-scope-guides-and-brace-anchoring/LSN-0034-active-scope-gutter-and-frontend-owned-structural-anchors.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0017","status":"done","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0035","file":"discussion/lessons/DSC-0017-studio-editor-inline-type-hints-for-let-bindings/LSN-0035-frontend-owned-inline-hints-with-decorative-inline-rendering.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0018","status":"done","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0031","file":"discussion/lessons/DSC-0018-studio-project-local-studio-state-under-dot-studio/LSN-0031-project-local-studio-state-and-lifecycle-safe-layout-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0019","status":"done","ticket":"studio-project-local-setup-separate-from-main-studio-state","title":"Separate project-local setup from the main Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","setup","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0032","file":"discussion/lessons/DSC-0019-studio-project-local-setup-separate-from-main-studio-state/LSN-0032-separate-project-config-from-session-restoration-state.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0020","status":"done","ticket":"studio-editor-indentation-policy-and-project-setup","title":"Indentation Policy, Status-Bar Semantics, and Project-Local Editor Setup","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","editor","indentation","tabs","setup","dot-studio","configuration","ux"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0033","file":"discussion/lessons/DSC-0020-studio-editor-indentation-policy-and-project-setup/LSN-0033-setup-owned-indentation-policy-and-project-bootstrap-defaults.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0021","status":"done","ticket":"studio-frontend-editor-write-and-save-wave","title":"Enable Frontend Editing and Save in the Studio Code Editor","created_at":"2026-04-04","updated_at":"2026-04-06","tags":["studio","editor","frontend","write","save","vfs","lsp","pbs","access-policy"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0021-studio-frontend-editor-write-and-save-wave/LSN-0036-vfs-owned-frontend-edit-and-save-wave.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0022","status":"done","ticket":"studio-play-stop-cartridge-flow","title":"Wire the Studio Play/Stop button to shipper phase 1 cartridge preparation and runtime execution","created_at":"2026-04-06","updated_at":"2026-04-07","tags":["studio","play-stop","shipper","runtime","cartridge","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0043","file":"discussion/lessons/DSC-0022-studio-play-stop-and-debugger-integration/LSN-0043-studio-play-stop-and-debugger-integration.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0023","status":"done","ticket":"gradle-version-catalog-migration","title":"Move dependency version management to Version Catalog (TOML)","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["gradle","buildSrc","dependency-management","version-catalog"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0023-gradle-version-catalog-migration/LSN-0037-gradle-version-catalog-adoption.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
@@ -1,35 +0,0 @@
{"type":"meta","next_id":{"DSC":35,"AGD":38,"DEC":35,"PLN":75,"LSN":49,"CLSN":1}}
{"type":"discussion","id":"DSC-0034","status":"done","ticket":"frontend-semantic-host-projection-flexibility","title":"Frontend semantic vocabulary flexibility and declarative host projection","created_at":"2026-05-06","updated_at":"2026-05-07","tags":["compiler","compiler-general","frontend","semantics","vscode","host-projection","lsp"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0034-frontend-semantic-host-projection-flexibility/LSN-0048-frontend-owned-semantic-vocabularies-with-declarative-host-projection.md","status":"done","created_at":"2026-05-07","updated_at":"2026-05-07"}]}
{"type":"discussion","id":"DSC-0033","status":"in_progress","ticket":"frontend-visual-theme-spec-and-css-retirement","title":"Frontend visual theme spec and retirement of host-consumed semantic CSS","created_at":"2026-05-06","updated_at":"2026-05-06","tags":["compiler","compiler-general","frontend","presentation","theming","studio","vscode","lsp","pbs"],"agendas":[{"id":"AGD-0036","file":"AGD-0036-frontend-visual-theme-spec-and-css-retirement.md","status":"accepted","created_at":"2026-05-06","updated_at":"2026-05-06"}],"decisions":[{"id":"DEC-0033","file":"DEC-0033-frontend-visual-theme-spec-and-css-retirement.md","status":"accepted","created_at":"2026-05-06","updated_at":"2026-05-06","ref_agenda":"AGD-0036"}],"plans":[{"id":"PLN-0068","file":"PLN-0068-frontend-visual-contract-and-pbs-migration.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]},{"id":"PLN-0069","file":"PLN-0069-lsp-visual-theme-transport-and-selection.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]},{"id":"PLN-0070","file":"PLN-0070-studio-visual-theme-adapter-and-css-retirement.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]},{"id":"PLN-0071","file":"PLN-0071-vscode-dynamic-theme-translation-adapter.md","status":"open","created_at":"2026-05-06","updated_at":"2026-05-06","ref_decisions":["DEC-0033"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0032","status":"done","ticket":"studio-new-lsp-api-and-v1-boundary","title":"Novo boundary entre lsp-api, lsp-v1 e a extensao VS Code","created_at":"2026-05-05","updated_at":"2026-05-07","tags":["studio","lsp","vscode","protocol","api","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0047","file":"discussion/lessons/DSC-0032-studio-new-lsp-api-and-v1-boundary/LSN-0047-project-scoped-lsp-boundary-and-protocol-containment.md","status":"done","created_at":"2026-05-07","updated_at":"2026-05-07"}]}
{"type":"discussion","id":"DSC-0031","status":"in_progress","ticket":"studio-editor-workspace-cleanup","title":"Limpeza completa do Workspace Editor do Studio e remoção dos acoplamentos legados","created_at":"2026-05-05","updated_at":"2026-05-05","tags":["studio","editor","cleanup","vfs","lsp","migration"],"agendas":[{"id":"AGD-0034","file":"AGD-0034-vscode-editor-migration-feasibility.md","status":"accepted","created_at":"2026-05-05","updated_at":"2026-05-05"}],"decisions":[{"id":"DEC-0031","file":"DEC-0031-studio-editor-workspace-cleanup.md","status":"in_progress","created_at":"2026-05-05","updated_at":"2026-05-05","ref_agenda":"AGD-0034"}],"plans":[{"id":"PLN-0062","file":"PLN-0062-shell-session-and-state-cleanup-after-editor-removal.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0031"]},{"id":"PLN-0063","file":"PLN-0063-legacy-lsp-and-vfs-module-removal-with-runtime-preservation.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0031"]},{"id":"PLN-0064","file":"PLN-0064-normative-test-and-lesson-cleanup-for-editor-stack-removal.md","status":"done","created_at":"2026-05-05","updated_at":"2026-05-05","ref_decisions":["DEC-0031"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0030","status":"done","ticket":"studio-scene-pack-runtime-binary-contract","title":"Studio scene pack contract for runtime SCENE binary payload","created_at":"2026-04-24","updated_at":"2026-05-01","tags":["studio","packer","runtime","scene","asset-pack","binary-format","tiled"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0030-studio-scene-pack-runtime-binary-contract/LSN-0046-canonical-scene-owns-editorial-truth-while-pack-stays-request-driven.md","status":"done","created_at":"2026-05-01","updated_at":"2026-05-01"}]}
{"type":"discussion","id":"DSC-0029","status":"done","ticket":"studio-frame-composer-syscall-and-sprite-alignment","title":"Studio Alignment with Runtime FrameComposer Syscalls and Sprite Composition","created_at":"2026-04-18","updated_at":"2026-04-18","tags":["studio","compiler","pbs","stdlib","runtime-alignment","abi","syscall","frame-composer","sprites"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0041","file":"discussion/lessons/DSC-0029-studio-frame-composer-syscall-and-sprite-alignment/LSN-0041-composer-must-own-public-sprite-composition.md","status":"done","created_at":"2026-04-18","updated_at":"2026-04-18"}]}
{"type":"discussion","id":"DSC-0028","status":"done","ticket":"studio-tiled-parser-assets-scene-asset-type","title":"Tiled Parser and Scene Asset-Type Ownership in Assets Workspace","created_at":"2026-04-15","updated_at":"2026-04-23","tags":["studio","assets","scene","tiled","parser","asset-type"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0028-studio-tiled-parser-assets-scene-asset-type/LSN-0045-asset-owned-scene-bank-and-tiled-xml-workflow.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0027","status":"abandoned","ticket":"studio-scene-workspace","title":"Scene Workspace for SCENE Authoring","created_at":"2026-04-14","updated_at":"2026-04-15","tags":["studio","workspace","scene","tilemap","asset","runtime-alignment"],"agendas":[{"id":"AGD-0029","file":"AGD-0029-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted agenda and its downstream work."}],"decisions":[{"id":"DEC-0026","file":"DEC-0026-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_agenda":"AGD-0029","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted decision and stop using it as normative guidance."}],"plans":[{"id":"PLN-0049","file":"PLN-0049-scene-workspace-spec-and-boundary-propagation.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0050","file":"PLN-0050-scene-workspace-shell-and-project-state-foundations.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0051","file":"PLN-0051-scene-artifact-and-assets-handoff-contract.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0052","file":"PLN-0052-scene-workspace-wave-1-tilemap-editor.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."}],"lessons":[]}
{"type":"discussion","id":"DSC-0026","status":"done","ticket":"glyph-bank-naming-alignment-with-runtime","title":"Glyph Bank Naming Alignment with Runtime DEC-0006","created_at":"2026-04-10","updated_at":"2026-04-10","tags":["packer","studio","naming","asset-contract","runtime-alignment","glyph-bank"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0040","file":"discussion/lessons/DSC-0026-glyph-bank-naming-alignment-with-runtime/LSN-0040-glyph-bank-artifact-naming-alignment.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0025","status":"done","ticket":"packer-pipeline-metadata-ownership","title":"Pipeline Metadata Ownership and Runtime Contract","created_at":"2026-04-09","updated_at":"2026-04-10","tags":["packer","metadata","runtime-contract","tooling","studio"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0039","file":"discussion/lessons/DSC-0025-packer-pipeline-metadata-ownership/LSN-0039-runtime-header-boundary-and-tooling-owned-pipeline-metadata.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0024","status":"done","ticket":"jacoco-reports-consolidation","title":"JaCoCo Reports Consolidation in Gradle","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["infra","gradle","jacoco","coverage","jenkins"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0038","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0038-jacoco-reports-consolidation.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"},{"id":"LSN-0044","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0044-jenkins-jacoco-alignment.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-04-23","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0002-palette-management-in-studio/LSN-0042-schema-driven-palette-authoring-and-local-metadata-events.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"abandoned","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-04-24","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"abandoned","created_at":"2026-03-26","updated_at":"2026-04-24","_override_reason":"Explicit user request on 2026-04-24 to abandon AGD-0004 because the agenda is no longer valid."}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-04-07","tags":["studio","debugger","workspace","integration","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"done","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0034","file":"discussion/lessons/DSC-0016-studio-editor-scope-guides-and-brace-anchoring/LSN-0034-active-scope-gutter-and-frontend-owned-structural-anchors.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0017","status":"done","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0035","file":"discussion/lessons/DSC-0017-studio-editor-inline-type-hints-for-let-bindings/LSN-0035-frontend-owned-inline-hints-with-decorative-inline-rendering.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0018","status":"done","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0031","file":"discussion/lessons/DSC-0018-studio-project-local-studio-state-under-dot-studio/LSN-0031-project-local-studio-state-and-lifecycle-safe-layout-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0019","status":"done","ticket":"studio-project-local-setup-separate-from-main-studio-state","title":"Separate project-local setup from the main Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","setup","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0032","file":"discussion/lessons/DSC-0019-studio-project-local-setup-separate-from-main-studio-state/LSN-0032-separate-project-config-from-session-restoration-state.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0020","status":"done","ticket":"studio-editor-indentation-policy-and-project-setup","title":"Indentation Policy, Status-Bar Semantics, and Project-Local Editor Setup","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","editor","indentation","tabs","setup","dot-studio","configuration","ux"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0033","file":"discussion/lessons/DSC-0020-studio-editor-indentation-policy-and-project-setup/LSN-0033-setup-owned-indentation-policy-and-project-bootstrap-defaults.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0021","status":"done","ticket":"studio-frontend-editor-write-and-save-wave","title":"Enable Frontend Editing and Save in the Studio Code Editor","created_at":"2026-04-04","updated_at":"2026-04-06","tags":["studio","editor","frontend","write","save","vfs","lsp","pbs","access-policy"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0021-studio-frontend-editor-write-and-save-wave/LSN-0036-vfs-owned-frontend-edit-and-save-wave.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0022","status":"done","ticket":"studio-play-stop-cartridge-flow","title":"Wire the Studio Play/Stop button to shipper phase 1 cartridge preparation and runtime execution","created_at":"2026-04-06","updated_at":"2026-04-07","tags":["studio","play-stop","shipper","runtime","cartridge","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0043","file":"discussion/lessons/DSC-0022-studio-play-stop-and-debugger-integration/LSN-0043-studio-play-stop-and-debugger-integration.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0023","status":"done","ticket":"gradle-version-catalog-migration","title":"Move dependency version management to Version Catalog (TOML)","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["gradle","buildSrc","dependency-management","version-catalog"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0023-gradle-version-catalog-migration/LSN-0037-gradle-version-catalog-adoption.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
-66
View File
@@ -1,66 +0,0 @@
{"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":55,"PLN":134,"LSN":71,"CLSN":1}}
{"type":"discussion","id":"DSC-0065","status":"done","ticket":"multi-frontend-avoid-premature-abstractions","title":"Evitar abstracoes prematuras na preparacao multi-frontend","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","studio","frontend","architecture","multi-frontend","simplicity"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0067","file":"discussion/lessons/DSC-0065-multi-frontend-avoid-premature-abstractions/LSN-0067-multi-frontend-phase-rejects-premature-infrastructure.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0064","status":"done","ticket":"multi-frontend-architectural-tests","title":"Testes arquiteturais para fronteiras multi-frontend","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","studio","frontend","architecture","tests","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0066","file":"discussion/lessons/DSC-0064-multi-frontend-architectural-tests/LSN-0066-archunit-guards-java-multi-frontend-boundaries.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0063","status":"done","ticket":"multi-frontend-synthetic-test-frontend","title":"Frontend sintetico de teste para provar neutralidade do pipeline","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","frontend","tests","backend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0065","file":"discussion/lessons/DSC-0063-multi-frontend-synthetic-test-frontend/LSN-0065-synthetic-test-frontend-proves-pipeline-neutrality.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0062","status":"done","ticket":"multi-frontend-pvm-neutrality","title":"Neutralidade da PVM e identificacao PBX independente de PBS","created_at":"2026-07-15","updated_at":"2026-09-18","tags":["vm-arch","runtime","pvm","pbx","compiler","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0061","file":"discussion/lessons/DSC-0062-multi-frontend-pvm-neutrality/LSN-0061-pbx-runtime-boundary.md","status":"done","created_at":"2026-09-18","updated_at":"2026-09-18"}]}
{"type":"discussion","id":"DSC-0061","status":"done","ticket":"multi-frontend-sdk-canonical-definition","title":"Auditoria e centralizacao gradual da definicao canonica do SDK","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","sdk","stdlib","hostcalls","intrinsics","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0064","file":"discussion/lessons/DSC-0061-multi-frontend-sdk-canonical-definition/LSN-0064-runtime-owns-console-abi-pbs-is-delivery.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0060","status":"done","ticket":"multi-frontend-validation-boundaries","title":"Separar validacoes de linguagem e validacoes de plataforma","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","compiler-pbs","backend","validation","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0063","file":"discussion/lessons/DSC-0060-multi-frontend-validation-boundaries/LSN-0063-language-vs-platform-validation-ownership.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0059","status":"done","ticket":"multi-frontend-common-lifecycle","title":"Extrair lifecycle comum das responsabilidades do frontend PBS","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","compiler-pbs","lifecycle","backend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0062","file":"discussion/lessons/DSC-0059-multi-frontend-common-lifecycle/LSN-0062-common-lifecycle-assembly-stage.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0058","status":"done","ticket":"multi-frontend-serializable-ir","title":"Manter a IR comum serializavel por design","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","ir","backend","serialization","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0060","file":"discussion/lessons/DSC-0058-multi-frontend-serializable-ir/LSN-0060-data-contract-first-for-serializable-irbackend.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
{"type":"discussion","id":"DSC-0057","status":"done","ticket":"multi-frontend-frontend-backend-contract","title":"Estabilizar contrato entre frontend e backend comum","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","compiler-pbs","ir","backend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0059","file":"discussion/lessons/DSC-0057-multi-frontend-frontend-backend-contract/LSN-0059-common-irbackend-handoff-and-backend-guardrails.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
{"type":"discussion","id":"DSC-0056","status":"done","ticket":"multi-frontend-remove-pbs-branches","title":"Generalizar o contrato LSP/editorial para frontends","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","compiler-pbs","studio","frontend","coupling","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0058","file":"discussion/lessons/DSC-0056-multi-frontend-remove-pbs-branches/LSN-0058-generic-frontend-editorial-contract-for-lsp.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
{"type":"discussion","id":"DSC-0055","status":"done","ticket":"multi-frontend-compiler-vs-language-services","title":"Separar compilacao de servicos editoriais de frontend","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","studio","lsp","editor","frontend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0056","file":"discussion/lessons/DSC-0055-multi-frontend-compiler-vs-language-services/LSN-0056-compile-first-frontends-with-optional-editorial-capabilities.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
{"type":"discussion","id":"DSC-0054","status":"done","ticket":"multi-frontend-provider-contract","title":"Introduzir provider completo de frontend","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","studio","frontend","registry","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0055","file":"discussion/lessons/DSC-0054-multi-frontend-provider-contract/LSN-0055-static-frontend-providers-before-plugin-architecture.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
{"type":"discussion","id":"DSC-0053","status":"open","ticket":"pbs-lsp-call-and-type-hierarchy","title":"PBS LSP Call and Type Hierarchy","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","call-hierarchy","type-hierarchy"],"agendas":[{"id":"AGD-0056","file":"AGD-0056-pbs-lsp-call-and-type-hierarchy.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0052","status":"open","ticket":"pbs-lsp-document-links","title":"PBS LSP Document Links","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","document-links","imports"],"agendas":[{"id":"AGD-0055","file":"AGD-0055-pbs-lsp-document-links.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0051","status":"open","ticket":"pbs-lsp-diagnostics-ux","title":"PBS LSP Diagnostics UX","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","diagnostics","ux"],"agendas":[{"id":"AGD-0054","file":"AGD-0054-pbs-lsp-diagnostics-ux.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0050","status":"open","ticket":"pbs-lsp-folding-and-selection-ranges","title":"PBS LSP Folding and Selection Ranges","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","folding","selection-range"],"agendas":[{"id":"AGD-0053","file":"AGD-0053-pbs-lsp-folding-and-selection-ranges.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0049","status":"open","ticket":"pbs-lsp-completion-depth","title":"PBS LSP Completion Depth","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","completion"],"agendas":[{"id":"AGD-0052","file":"AGD-0052-pbs-lsp-completion-depth.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0048","status":"open","ticket":"pbs-lsp-performance-cache-and-snapshots","title":"PBS LSP Performance Cache and Snapshots","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","performance","caching"],"agendas":[{"id":"AGD-0051","file":"AGD-0051-pbs-lsp-performance-cache-and-snapshots.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"pbs-lsp-semantic-tokens-semantic-classification","title":"PBS LSP Semantic Token Classification","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","semantic-tokens"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-pbs-lsp-semantic-token-classification.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0046","status":"open","ticket":"pbs-lsp-import-assistance","title":"PBS LSP Import Assistance","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","imports","completion"],"agendas":[{"id":"AGD-0049","file":"AGD-0049-pbs-lsp-import-assistance.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0045","status":"open","ticket":"pbs-lsp-formatting","title":"PBS LSP Formatting","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","formatting"],"agendas":[{"id":"AGD-0048","file":"AGD-0048-pbs-lsp-formatting.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0044","status":"open","ticket":"pbs-lsp-code-actions","title":"PBS LSP Code Actions and Quick Fixes","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","code-actions","quick-fix"],"agendas":[{"id":"AGD-0047","file":"AGD-0047-pbs-lsp-code-actions-and-quick-fixes.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0043","status":"open","ticket":"pbs-lsp-rename-symbol","title":"PBS LSP Rename Symbol","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","rename"],"agendas":[{"id":"AGD-0046","file":"AGD-0046-pbs-lsp-rename-symbol.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0042","status":"open","ticket":"pbs-lsp-workspace-symbols","title":"PBS LSP Workspace Symbols","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","workspace-symbols"],"agendas":[{"id":"AGD-0045","file":"AGD-0045-pbs-lsp-workspace-symbols.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0041","status":"done","ticket":"pbs-lsp-document-symbols-outline","title":"PBS LSP Document Symbols and Outline","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","outline","document-symbols"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0070","file":"discussion/lessons/DSC-0041-pbs-lsp-document-symbols-outline/LSN-0070-pbs-outline-is-an-ast-backed-document-symbol-tree.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
{"type":"discussion","id":"DSC-0040","status":"done","ticket":"pbs-lsp-find-references","title":"PBS LSP Find References","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","references"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0069","file":"discussion/lessons/DSC-0040-pbs-lsp-find-references/LSN-0069-pbs-find-references-is-the-physical-inverse-of-definition.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
{"type":"discussion","id":"DSC-0039","status":"done","ticket":"pbs-lsp-go-to-definition","title":"PBS LSP Go to Definition","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","definition"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0068","file":"discussion/lessons/DSC-0039-pbs-lsp-go-to-definition/LSN-0068-pbs-go-to-definition-uses-editorial-lookup-and-physical-files.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
{"type":"discussion","id":"DSC-0038","status":"done","ticket":"studio-packer-rgba8888-asset-pipeline","title":"Studio and Packer RGBA8888 Asset Pipeline Alignment","created_at":"2026-05-23","updated_at":"2026-07-14","tags":["studio","packer","assets","glyph-bank","palette","rgba8888","runtime-alignment"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0038-studio-packer-rgba8888-asset-pipeline/LSN-0053-rgba8888-is-the-canonical-studio-packer-palette-contract.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"pbs-autocomplete-parameter-names","title":"PBS autocomplete parameter names for stdlib and method calls","created_at":"2026-05-08","updated_at":"2026-05-14","tags":["compiler-pbs","studio","lsp","autocomplete","signature-help","stdlib"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0037-pbs-autocomplete-parameter-names/LSN-0052-canonical-callable-parameter-names-through-pbs-editor-assistance.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14"}]}
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"pbs-symbol-documentation-and-hover-markdown","title":"Modelo de documentacao de simbolos em PBS e consumo markdown no hover","created_at":"2026-05-08","updated_at":"2026-07-15","tags":["compiler","compiler-pbs","studio","lsp","vscode","editor","hover","documentation","markdown"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0057","file":"discussion/lessons/DSC-0036-pbs-symbol-documentation-and-hover-markdown/LSN-0057-compiler-owned-pbs-doc-markdown-for-editor-assistance.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
{"type":"discussion","id":"DSC-0035","status":"done","ticket":"pbs-lsp-editor-assistance-wave-1","title":"Wave 1 de assistencia editorial via LSP para PBS no VS Code","created_at":"2026-05-08","updated_at":"2026-05-08","tags":["studio","lsp","vscode","compiler","compiler-pbs","editor","completion","hover","signature-help"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0051","file":"discussion/lessons/DSC-0035-pbs-lsp-editor-assistance-wave-1/LSN-0051-compiler-backed-editor-assistance-for-pbs.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
{"type":"discussion","id":"DSC-0034","status":"done","ticket":"frontend-semantic-host-projection-flexibility","title":"Frontend semantic vocabulary flexibility and declarative host projection","created_at":"2026-05-06","updated_at":"2026-05-07","tags":["compiler","compiler-general","frontend","semantics","vscode","host-projection","lsp"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0034-frontend-semantic-host-projection-flexibility/LSN-0048-frontend-owned-semantic-vocabularies-with-declarative-host-projection.md","status":"done","created_at":"2026-05-07","updated_at":"2026-05-07"}]}
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"frontend-visual-theme-spec-and-css-retirement","title":"Frontend visual theme spec and retirement of host-consumed semantic CSS","created_at":"2026-05-06","updated_at":"2026-05-08","tags":["compiler","compiler-general","frontend","presentation","theming","studio","vscode","lsp","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0033-frontend-visual-theme-spec-and-css-retirement/LSN-0050-frontend-owned-visual-themes-with-structured-contract-and-host-adapters.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
{"type":"discussion","id":"DSC-0032","status":"done","ticket":"studio-new-lsp-api-and-v1-boundary","title":"Novo boundary entre lsp-api, lsp-v1 e a extensao VS Code","created_at":"2026-05-05","updated_at":"2026-05-07","tags":["studio","lsp","vscode","protocol","api","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0047","file":"discussion/lessons/DSC-0032-studio-new-lsp-api-and-v1-boundary/LSN-0047-project-scoped-lsp-boundary-and-protocol-containment.md","status":"done","created_at":"2026-05-07","updated_at":"2026-05-07"}]}
{"type":"discussion","id":"DSC-0031","status":"done","ticket":"studio-editor-workspace-cleanup","title":"Limpeza completa do Workspace Editor do Studio e remoção dos acoplamentos legados","created_at":"2026-05-05","updated_at":"2026-05-08","tags":["studio","editor","cleanup","vfs","lsp","migration"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0049","file":"discussion/lessons/DSC-0031-studio-editor-workspace-cleanup/LSN-0049-remove-the-embedded-editor-stack-before-rebuilding-code-workflows.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
{"type":"discussion","id":"DSC-0030","status":"done","ticket":"studio-scene-pack-runtime-binary-contract","title":"Studio scene pack contract for runtime SCENE binary payload","created_at":"2026-04-24","updated_at":"2026-05-01","tags":["studio","packer","runtime","scene","asset-pack","binary-format","tiled"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0030-studio-scene-pack-runtime-binary-contract/LSN-0046-canonical-scene-owns-editorial-truth-while-pack-stays-request-driven.md","status":"done","created_at":"2026-05-01","updated_at":"2026-05-01"}]}
{"type":"discussion","id":"DSC-0029","status":"done","ticket":"studio-frame-composer-syscall-and-sprite-alignment","title":"Studio Alignment with Runtime FrameComposer Syscalls and Sprite Composition","created_at":"2026-04-18","updated_at":"2026-04-18","tags":["studio","compiler","pbs","stdlib","runtime-alignment","abi","syscall","frame-composer","sprites"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0041","file":"discussion/lessons/DSC-0029-studio-frame-composer-syscall-and-sprite-alignment/LSN-0041-composer-must-own-public-sprite-composition.md","status":"done","created_at":"2026-04-18","updated_at":"2026-04-18"}]}
{"type":"discussion","id":"DSC-0028","status":"done","ticket":"studio-tiled-parser-assets-scene-asset-type","title":"Tiled Parser and Scene Asset-Type Ownership in Assets Workspace","created_at":"2026-04-15","updated_at":"2026-04-23","tags":["studio","assets","scene","tiled","parser","asset-type"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0028-studio-tiled-parser-assets-scene-asset-type/LSN-0045-asset-owned-scene-bank-and-tiled-xml-workflow.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0027","status":"abandoned","ticket":"studio-scene-workspace","title":"Scene Workspace for SCENE Authoring","created_at":"2026-04-14","updated_at":"2026-04-15","tags":["studio","workspace","scene","tilemap","asset","runtime-alignment"],"agendas":[{"id":"AGD-0029","file":"AGD-0029-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted agenda and its downstream work."}],"decisions":[{"id":"DEC-0026","file":"DEC-0026-studio-scene-workspace.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_agenda":"AGD-0029","_override_reason":"Explicit user request on 2026-04-15 to abandon the accepted decision and stop using it as normative guidance."}],"plans":[{"id":"PLN-0049","file":"PLN-0049-scene-workspace-spec-and-boundary-propagation.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0050","file":"PLN-0050-scene-workspace-shell-and-project-state-foundations.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0051","file":"PLN-0051-scene-artifact-and-assets-handoff-contract.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."},{"id":"PLN-0052","file":"PLN-0052-scene-workspace-wave-1-tilemap-editor.md","status":"abandoned","created_at":"2026-04-14","updated_at":"2026-04-15","ref_decisions":["DEC-0026"],"_override_reason":"Explicit user request on 2026-04-15 to abandon all plans derived from DEC-0026."}],"lessons":[]}
{"type":"discussion","id":"DSC-0026","status":"done","ticket":"glyph-bank-naming-alignment-with-runtime","title":"Glyph Bank Naming Alignment with Runtime DEC-0006","created_at":"2026-04-10","updated_at":"2026-04-10","tags":["packer","studio","naming","asset-contract","runtime-alignment","glyph-bank"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0040","file":"discussion/lessons/DSC-0026-glyph-bank-naming-alignment-with-runtime/LSN-0040-glyph-bank-artifact-naming-alignment.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0025","status":"done","ticket":"packer-pipeline-metadata-ownership","title":"Pipeline Metadata Ownership and Runtime Contract","created_at":"2026-04-09","updated_at":"2026-04-10","tags":["packer","metadata","runtime-contract","tooling","studio"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0039","file":"discussion/lessons/DSC-0025-packer-pipeline-metadata-ownership/LSN-0039-runtime-header-boundary-and-tooling-owned-pipeline-metadata.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
{"type":"discussion","id":"DSC-0024","status":"done","ticket":"jacoco-reports-consolidation","title":"JaCoCo Reports Consolidation in Gradle","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["infra","gradle","jacoco","coverage","jenkins"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0038","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0038-jacoco-reports-consolidation.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"},{"id":"LSN-0044","file":"discussion/lessons/DSC-0024-jacoco-reports-consolidation/LSN-0044-jenkins-jacoco-alignment.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-04-23","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0002-palette-management-in-studio/LSN-0042-schema-driven-palette-authoring-and-local-metadata-events.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"abandoned","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-04-24","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"abandoned","created_at":"2026-03-26","updated_at":"2026-04-24","_override_reason":"Explicit user request on 2026-04-24 to abandon AGD-0004 because the agenda is no longer valid."}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"done","ticket":"variable-tile-bank-palette-serialization","title":"Variable Glyph Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-07-14","tags":["packer","legacy-import","glyph-bank","palette-serialization","rgba8888","runtime-alignment"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0005-variable-glyph-bank-palette-serialization/LSN-0054-runtime-owned-variable-glyph-palette-counts.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"studio-debugger-workspace-integration","title":"Integrate ../debugger into Studio as a dedicated workspace","created_at":"2026-03-30","updated_at":"2026-04-07","tags":["studio","debugger","workspace","integration","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"studio-code-editor-workspace-foundations","title":"Establish Code Editor workspace foundations in Studio without LSP","created_at":"2026-03-30","updated_at":"2026-03-31","tags":["studio","editor","workspace","multi-frontend","lsp-deferred"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0010-studio-code-editor-workspace-foundations/LSN-0026-read-only-editor-foundations-and-semantic-deferral.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0011","status":"done","ticket":"compiler-analyze-compile-build-pipeline-split","title":"Split compiler pipeline into analyze, compile, and build entrypoints","created_at":"2026-03-30","updated_at":"2026-03-30","tags":["compiler","pipeline","artifacts","build","analysis"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0011-compiler-analyze-compile-build-pipeline-split/LSN-0025-compiler-pipeline-entrypoints-and-result-boundaries.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0012","status":"done","ticket":"studio-editor-document-vfs-boundary","title":"Definir um boundary de VFS documental para tree/view/open files no Code Editor do Studio","created_at":"2026-03-31","updated_at":"2026-03-31","tags":["studio","editor","workspace","vfs","filesystem","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0027","file":"discussion/lessons/DSC-0012-studio-editor-document-vfs-boundary/LSN-0027-project-document-vfs-and-session-owned-editor-boundary.md","status":"done","created_at":"2026-03-31","updated_at":"2026-03-31"}]}
{"type":"discussion","id":"DSC-0013","status":"done","ticket":"studio-editor-write-wave-supported-non-frontend-files","title":"Definir a wave inicial de edicao no Code Editor apenas para arquivos aceitos e nao relacionados ao FE","created_at":"2026-03-31","updated_at":"2026-04-02","tags":["studio","editor","workspace","write","read-only","vfs","frontend-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0013-studio-editor-write-wave-supported-non-frontend-files/LSN-0028-controlled-editor-write-wave-and-read-only-frontend-semantic-phase.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0014","status":"done","ticket":"studio-frontend-owned-semantic-editor-presentation","title":"Definir ownership do schema visual semantico do editor por frontend","created_at":"2026-04-02","updated_at":"2026-04-02","tags":["studio","editor","frontend","presentation","semantic-highlighting","compiler","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0029","file":"discussion/lessons/DSC-0014-studio-frontend-owned-semantic-editor-presentation/LSN-0029-frontend-owned-semantic-presentation-descriptor-and-host-consumption.md","status":"done","created_at":"2026-04-02","updated_at":"2026-04-02"}]}
{"type":"discussion","id":"DSC-0015","status":"done","ticket":"pbs-service-facade-reserved-metadata","title":"SDK Service Bodies Calling Builtin/Intrinsic Proxies as Ordinary PBS Code","created_at":"2026-04-03","updated_at":"2026-04-03","tags":["compiler","pbs","sdk","stdlib","lowering","service","intrinsic","sdk-interface"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0030","file":"discussion/lessons/DSC-0015-pbs-service-facade-reserved-metadata/LSN-0030-sdk-service-bodies-over-private-reserved-proxies.md","status":"done","created_at":"2026-04-03","updated_at":"2026-04-03"}]}
{"type":"discussion","id":"DSC-0016","status":"done","ticket":"studio-editor-scope-guides-and-brace-anchoring","title":"Scope Guides do Code Editor com ancoragem exata em braces e destaque do escopo ativo","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","scope-guides","braces","semantic-read","frontend-contract"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0034","file":"discussion/lessons/DSC-0016-studio-editor-scope-guides-and-brace-anchoring/LSN-0034-active-scope-gutter-and-frontend-owned-structural-anchors.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0017","status":"done","ticket":"studio-editor-inline-type-hints-for-let-bindings","title":"Inline Type Hints for Let Bindings in the Studio Editor","created_at":"2026-04-03","updated_at":"2026-04-06","tags":["studio","editor","inline-hints","inlay-hints","lsp","pbs","type-inference"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0035","file":"discussion/lessons/DSC-0017-studio-editor-inline-type-hints-for-let-bindings/LSN-0035-frontend-owned-inline-hints-with-decorative-inline-rendering.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0018","status":"done","ticket":"studio-project-local-studio-state-under-dot-studio","title":"Persist project-local Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","shell","layout","setup"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0031","file":"discussion/lessons/DSC-0018-studio-project-local-studio-state-under-dot-studio/LSN-0031-project-local-studio-state-and-lifecycle-safe-layout-restoration.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0019","status":"done","ticket":"studio-project-local-setup-separate-from-main-studio-state","title":"Separate project-local setup from the main Studio state under .studio","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","project-session","project-state","persistence","dot-studio","setup","boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0032","file":"discussion/lessons/DSC-0019-studio-project-local-setup-separate-from-main-studio-state/LSN-0032-separate-project-config-from-session-restoration-state.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0020","status":"done","ticket":"studio-editor-indentation-policy-and-project-setup","title":"Indentation Policy, Status-Bar Semantics, and Project-Local Editor Setup","created_at":"2026-04-04","updated_at":"2026-04-04","tags":["studio","editor","indentation","tabs","setup","dot-studio","configuration","ux"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0033","file":"discussion/lessons/DSC-0020-studio-editor-indentation-policy-and-project-setup/LSN-0033-setup-owned-indentation-policy-and-project-bootstrap-defaults.md","status":"done","created_at":"2026-04-04","updated_at":"2026-04-04"}]}
{"type":"discussion","id":"DSC-0021","status":"done","ticket":"studio-frontend-editor-write-and-save-wave","title":"Enable Frontend Editing and Save in the Studio Code Editor","created_at":"2026-04-04","updated_at":"2026-04-06","tags":["studio","editor","frontend","write","save","vfs","lsp","pbs","access-policy"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0021-studio-frontend-editor-write-and-save-wave/LSN-0036-vfs-owned-frontend-edit-and-save-wave.md","status":"done","created_at":"2026-04-06","updated_at":"2026-04-06"}]}
{"type":"discussion","id":"DSC-0022","status":"done","ticket":"studio-play-stop-cartridge-flow","title":"Wire the Studio Play/Stop button to shipper phase 1 cartridge preparation and runtime execution","created_at":"2026-04-06","updated_at":"2026-04-07","tags":["studio","play-stop","shipper","runtime","cartridge","shell"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0043","file":"discussion/lessons/DSC-0022-studio-play-stop-and-debugger-integration/LSN-0043-studio-play-stop-and-debugger-integration.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
{"type":"discussion","id":"DSC-0023","status":"done","ticket":"gradle-version-catalog-migration","title":"Move dependency version management to Version Catalog (TOML)","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["gradle","buildSrc","dependency-management","version-catalog"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0023-gradle-version-catalog-migration/LSN-0037-gradle-version-catalog-adoption.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]}
@@ -0,0 +1,149 @@
---
id: LSN-0071
ticket: pbs-lsp-workspace-symbols
title: PBS workspace symbols are a physical named-declaration search
created: 2026-09-21
tags: [studio, lsp, vscode, compiler-pbs, editor, workspace-symbols]
---
# PBS workspace symbols are a physical named-declaration search
## Original Problem
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), find-references (`LSN-0069`), and an AST-backed outline of the open `.pbs` file (`LSN-0070`). VS Code workspace search (`Ctrl+T` / `workspace/symbol`) stayed empty.
The risk was treating workspace symbols as a second outline, inventing a `SymbolId` index, waiting for snapshot cache (`AGD-0051`), or returning stdlib/SDK hits whose declarations are still virtual paths (`/virtual/stdlib`). Workspace symbols is a jump. Outline is not.
## Consolidated Decision
PBS Workspace Symbols is the LSP projection of a **flat named-declaration search** over **regular filesystem files** of the current analysis, flattening the **same outline set** and using the **same physical-file destination policy** as definition.
Durable locks from `DEC-0055` (AGD-0045 Q1 A, Q2 A, Q3 A, Q4 A, Q5 A, Q6 first-wave exclusions):
1. Emit only declarations whose `fileTable` handle is a regular filesystem file. Virtual stdlib/SDK, including `/virtual/stdlib`, is omitted. Do not invent virtual documents, `untitled:` buffers, or synthetic URIs.
2. `workspace/symbol` does not require an open text document. The server obtains the project analysis surface (`astByFile` / `projectSurface`) from `analyze()`. Missing surface → empty list.
3. The set is the flatten, file by file, of the named-declaration tree locked by outline (`LSN-0070`):
- `fn` → Function;
- `declare struct` → Struct plus fields, `ctor`s, methods;
- `declare service` → Service plus methods;
- `declare contract` → Contract plus signatures;
- `declare host` → Host plus signatures;
- `declare builtin type` → Builtin type plus projection fields and signatures;
- `declare enum` → Enum plus cases;
- `declare error` → Error plus labels;
- `declare callback` → Callback;
- `declare global` / `const` → Global / Const;
- `implements Contract for Owner` → `contractName`, kind CONTRACT, `detail` = owner, plus methods.
Locals, parameters, `this`, imports, and comments stay out. Private fields stay in. Overloads stay sibling hits. Unnamed `InvalidDecl` is omitted. Named decls survive later semantic errors.
4. First wave is `.pbs` whose recovered root is `PbsAst.File`. `mod.barrel` (`BarrelFile`) stays empty. Presence, name, kind, `detail`, and spans come from recovered AST. Do not invent nodes from text search.
5. Query is a case-insensitive substring of `name` only. Blank query returns the full first-wave corpus. Do not match `detail`, path, `containerName`, or qualified `Vec.blend`. No fuzzy ranking, no `top N`. After the filter, order is stable by name, then path, then start offset.
6. `containerName` is the parent name for members and empty for top-level declarations. `detail` may repeat the outline AST signature. Attributes such as `[Init]` do not enter the name.
7. Keep the capability on aggregated `FrontendLanguageService`. Add `workspaceSymbols` (default empty) plus a flat DTO with `name`, `kind`, optional `detail`, `containerName`, absolute path, and offsets. Do not reuse pathless `FrontendDocumentSymbol`. PBS flattens in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Workspace Symbol SPI, `SymbolId`, `RefIndex`, or snapshot cache.
8. Advertise `workspaceSymbolProvider` when the frontend exposes a language service. Payload is flat `SymbolInformation`. Do not emit hierarchical `DocumentSymbol` on this request. Compile-only frontends stay empty. VS Code stays a thin client.
Spec 23 §8.3 now also states: workspace symbols are a flat search of named declarations in compiler-known physical source files of the current analysis; recovered syntax is enough; a missing analysis surface is empty; the request must not require an open document; a declaration without a physical file is omitted; this is not outline, folding, a persistent index, or navigation to virtual locations.
## Final Implementation
| Layer | What landed |
|---|---|
| PBS editorial | `PbsAstWorkspaceSymbols` flattens `PbsAstDocumentSymbols` and filters by name. `PbsEditorialSupportService.workspaceSymbols(ast, query)` delegates to that flatten. |
| Generic contract | `FrontendWorkspaceRequest` (`projectRoot`, `query`). `FrontendWorkspaceSymbol` carries path. `FrontendLanguageService.workspaceSymbols` defaults to `List.of()`. `prepareEditorialContext(FrontendPhaseContext)` defaults to empty so a workspace request can obtain project surface without a `FileId`. |
| PBS mapping | Project-level `prepareEditorialContext` attaches `fileTable` + `astByFile`. Regular `PbsAst.File` entries are flattened; non-regular handles are skipped. Results sort by name, path, offset. |
| LSP | `workspaceSymbolProvider`, `workspace/symbol` on `PrometeuWorkspaceService` (no document URI). `CompilerLanguageServiceBridge` analyzes the project with an empty overlay map. Mapper emits flat `SymbolInformation`. Nested enum/error hits with a container project to `EnumMember`. Compile-only frontends stay empty. |
| VS Code | Unchanged thin client. |
`workspace/symbol` in this wave reads the project on disk. Unsaved editor overlays are not shared into the search. Empty is honest until a later overlay/snapshot decision.
`mod.barrel` is still `BarrelFile`, not `PbsAst.File`. Empty barrel hits are the honest first-wave result.
Error case labels still have no per-label span. Flattened children reuse the parent `ErrorDecl` span, same as outline.
## Examples
Workspace search of a project file is the flatten of that file's outline, not imports or locals:
```pbs
import { Log } from @sdk:log;
fn helper() -> int { return 42; }
fn frame() -> void {
let local = 1;
helper(local);
}
```
Query `frame` → `frame`. Query `helper` → `helper`. Query empty → `helper`, `frame` (plus other physical decls), sorted. Not `Log`, not `local`.
Members keep a container; overloads stay siblings:
```pbs
declare struct Vec(x: int) {
ctor make(x: int) { return; }
fn blend(dx: int, dy: int) -> int { return dx; }
}
fn helper() -> int { return 42; }
fn helper(value: int) -> int { return value; }
```
Query `blend` → method `blend` with `containerName` `Vec`. Query `helper` → two hits. Query `Vec.blend` → empty (this wave matches `name` only).
Stdlib remains hover-only while the handle is virtual:
```pbs
import { Gfx } from @sdk:gfx;
Gfx.clear(0);
```
Query `Gfx` is empty. F12 on `Gfx.clear` is already empty (`LSN-0068`). Workspace search does not reopen that jump.
Recovered parse keeps the named decl:
```pbs
declare ;
fn ok() -> int { return 1; }
```
Query empty → `ok`. The unnamed `InvalidDecl` is omitted.
`[Init] fn init()` still names the symbol `init`.
## Pitfalls
Do not implement workspace symbols as workspace text search in `lsp-v1` or in the VS Code extension. It will lie about overloads, members, and imports.
Do not reuse `FrontendDocumentSymbol`. Outline is pathless because the host already has the document URI. Workspace symbols is a jump and must carry a path.
Do not require an open editor buffer to answer `workspace/symbol`. Analyze the project and walk `astByFile`.
Do not include `/virtual/stdlib` so Ctrl+T on `Gfx` “does something”. Empty is the honest result until those sources are regular files.
Do not wait for snapshot cache. References already walks the current analysis request-locally. Snapshots (`AGD-0051`) can make the walk cheaper without changing this contract.
Do not add a `SymbolId` index “for rename later”. Outline already named the declarations; definition already named the destination.
Do not match `containerName`, path, or `Vec.blend` in this wave. The query is a substring of `name`.
Do not emit hierarchical `DocumentSymbol` on `workspace/symbol`. That payload is outline.
Do not treat unsaved overlay absence as a missing feature of this contract. First-wave analysis is the project on disk.
Do not split a Workspace Symbol SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
Do not treat this lesson as closing rename, snapshots, folding, document links, or hierarchy.
## References
- Agenda: `AGD-0045` (Q1 A, Q2 A, Q3 A, Q4 A, Q5 A, Q6 first-wave exclusions)
- Decision: `DEC-0055`
- Plan: `PLN-0134`
- Spec 23 §8.3 — optional workspace symbols; physical-file-or-omit; no open document required
- `LSN-0070` — outline set this feature flattens
- `LSN-0068` — physical-file destination this feature reuses
- `LSN-0069` — project `astByFile` walk already exists for references
- `LSN-0058` — generic `FrontendLanguageService` for LSP
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
- `LSN-0067` — no SPI without a real in-repo consumer
- Still open: `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
@@ -0,0 +1,128 @@
---
id: LSN-0072
ticket: pbs-lsp-rename-symbol
title: PBS rename is a validated physical workspace edit
created: 2026-09-22
tags: [studio, lsp, vscode, compiler-pbs, editor, rename]
---
# PBS rename is a validated physical workspace edit
## Original Problem
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), find-references (`LSN-0069`), outline (`LSN-0070`), and workspace symbols (`LSN-0071`). Users still could not rename a symbol through the editor. Manual text edits miss uses or rewrite unrelated overloads, comments, strings, and same-name declarations.
The risk was a file-local rename, a lexeme replace, a new `SymbolId` / `RefIndex`, snapshot cache (`AGD-0051`) as a prerequisite, virtual stdlib documents, or a successful empty `WorkspaceEdit` that pretends the symbol changed.
## Consolidated Decision
PBS Rename Symbol is the LSP projection of a **validated `WorkspaceEdit`** over **physical identifier spans** of the **same identity definition already returns**.
Durable locks from `DEC-0056` (AGD-0046 Q1–Q6 = A):
1. Identity is the physical declaration-location set from definition. Do not text-search. Do not add `SymbolId` or a persistent `RefIndex`.
2. Sites are identifier tokens whose definition intersects that identity, plus identifier-sized declaration name spans. Overloads of the same name in the same owner rewrite together. Members rewrite only that member. Comments, strings, and homonyms of another identity stay.
3. Walk regular `fileTable` files of the current `analyze()` surface. Omit `/virtual/stdlib` and other non-regular handles. Every edit location must be a compiler-known physical source file.
4. Refuse when physical identity is empty: builtins, virtual stdlib/SDK, unresolved names, keywords, comments, strings, `this`, `Self`. Refuse `mod.barrel`. Refuse `declare error` case labels that have no per-label span.
5. Exception: a local or parameter name span is renameable even when definition at that offset is empty. Identity becomes that name span; uses are identifiers whose definition intersects it.
6. Refuse when the cursor lexeme is an import alias (`item.alias()` distinct from `item.name()`), including uses of that alias. Do not follow alias definition and rewrite the export. Export rename happens only when the cursor writes the original name. Export rewrite must not change `as Alias` tokens or uses that spell a differing alias.
7. `prepareRename` validates the cursor and returns the identifier range, or null. `rename` also validates the new name: PBS identifier, not a keyword, no collision in the same binding space (top-level `fn`/`service`/`global`/`const`, local/param in the same scope, field in the same struct, method in the same owner, case in the same enum), ignoring rewritten sites and the overload set. Failure is an LSP error. Never return a successful empty `WorkspaceEdit`. The server does not write files and does not rename paths.
8. Keep the capability on aggregated `FrontendLanguageService`. `prepareRename` defaults empty; `rename` defaults unsupported. PBS maps in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Rename SPI. Advertise `renameProvider` with `prepareProvider`. Compile-only stays unsupported. VS Code stays a thin client.
Spec 23 §8.3 now also states: rename is a validated workspace edit of identifier spans in compiler-known physical source files; identity is definition; local/param name spans remain renameable; alias, virtual, and error-label cursors refuse; invalid names and collisions are protocol errors, not empty success; the server does not write files; `prepareProvider` is advertised when rename is exposed.
## Final Implementation
| Layer | What landed |
|---|---|
| PBS editorial | `PbsEditorialSupportService.planRename` builds identity from definition or local/param name span, refuses aliases and error labels, walks `IDENTIFIER` tokens whose definition intersects identity and whose lexeme is the original name, then validates identifier/keyword/collision. |
| Generic contract | `FrontendLanguageService.prepareRename` defaults empty. `rename` defaults `FrontendRenameResult.unsupported()`. `FrontendRenameEdit` is path + offsets + `newText`. Applied results reject an empty edit list. |
| PBS mapping | `PBSFrontendLanguageService` reuses `projectDocuments` and `toFrontendLocation`. Empty physical identity is refuse, even if editorial sites exist on virtual handles. |
| LSP | `renameSupported`, `prepareRename`, `rename`. Mapper advertises `RenameOptions.prepareProvider`. Refused rename is `ResponseErrorException`, not an empty `WorkspaceEdit`. Compile-only does not advertise. |
| VS Code | Unchanged thin client. |
Stdlib and SDK modules remain virtual (`/virtual/stdlib/...`). F2 on `Gfx.clear` is refused, matching empty F12 / Shift+F12. Hover is unchanged.
`let total` at the binding itself still has empty definition. Rename uses the name span as identity so F2 on the binding works.
## Examples
Same-file function, including overloads and the declaring identifier. Comment and string stay:
```pbs
fn helper() -> int { return 1; }
fn helper(value: int) -> int { return value; }
fn frame() -> void {
helper();
helper(2);
// helper
let text = "helper";
}
```
F2 on `helper` → `aid` rewrites both declarations and both calls.
Local name span:
```pbs
fn frame() -> void {
let total = 1;
return total;
}
```
F2 on `let total` or on the use rewrites both identifier sites.
Alias is refused. Export rename keeps the local alias:
```pbs
import { Log as Logger } from @sdk:log;
Logger.info("a");
```
F2 on `Logger` or `Logger.info` is refused. F2 on a physical `Log` declaration rewrites the original name and `import { Log as Logger }`, and leaves `Logger` / `Logger.info`.
Builtins and virtual stdlib stay hover-only:
```pbs
let n: int = 1;
Gfx.clear(5);
```
Invalid new names (`fn`, `1ab`) and collisions (`helper` → existing `frame`) fail with an LSP error.
## Pitfalls
Do not implement rename as workspace text search in `lsp-v1` or in the VS Code extension. It will rewrite comments, strings, overloads of another identity, and import aliases.
Do not follow definition through an import alias. `Logger` currently resolves to `Log`'s span; a blind inverse-of-definition rename would rewrite the export.
Do not return a successful empty `WorkspaceEdit` for a refused cursor. The editor will treat that as “renamed”.
Do not skip the local/param name-span exception. F2 on `let total` is the common case, and definition there is empty.
Do not rewrite `declare error` case labels by using the parent `ErrorDecl` span. Those labels have no per-label span.
Do not wait for snapshot cache. Rename reuses the request-local walk already used by references.
Do not treat empty/refused stdlib rename as a missing feature. Virtual paths are not regular files.
Do not split a Rename SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
Do not treat this lesson as closing snapshots, folding, document links, hierarchy, code actions, formatting, file rename, or local-alias rename.
## References
- Agenda: `AGD-0046` (Q1–Q6 = A)
- Decision: `DEC-0056`
- Plan: `PLN-0135`
- Spec 23 §8.3 — optional rename; physical-file-or-empty; alias refuse; error instead of empty success; `prepareProvider`
- Spec: `docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md` §4.3–4.4
- `LSN-0068` — definition identity this feature writes
- `LSN-0069` — physical inverse that supplies usage sites
- `LSN-0051` — wave 1 deferred rename
- `LSN-0058` — generic `FrontendLanguageService` for LSP
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
- `LSN-0067` — no SPI without a real in-repo consumer
- Still open: `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
@@ -0,0 +1,130 @@
---
id: LSN-0073
ticket: pbs-lsp-code-actions
title: PBS quick fixes are frontend repairs transported by the LSP
created: 2026-09-22
tags: [studio, lsp, vscode, compiler-pbs, editor, code-actions, quick-fix]
---
# PBS quick fixes are frontend repairs transported by the LSP
## Original Problem
PBS diagnostics already reach the editor, but the server did not advertise `codeActionProvider`. A user could see a duplicate attribute or a bad `InitAllowed` and still had to repair it by hand.
The tempting shortcut was a code-to-edit table in the LSP. That shortcut does not work. Compiler `Diagnostic` values carry a stable code, phase, template, placeholders, span, and related locations, but the reserved-attribute reports use the short constructor: empty placeholders, and the English sentence is the only fine discriminator. `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` covers Doc without `markdown`, a wrong payload, empty markdown, an unknown argument, `InitAllowed` with arguments, an out-of-range `AssetLowering`, and a bad `Host` shape. A switch on the code cannot pick a safe edit without reading the message. Diagnostic wording is rendering, not identity. Code actions are an optional editorial capability: the frontend owns the meaning, and the LSP transports it.
## Consolidated Decision
PBS quick fix is one `WorkspaceEdit` tied to one diagnostic of the requested physical document. The frontend produces the repair from the syntax tree. The LSP does not invent it.
Durable locks from `DEC-0057` (AGD-0047: scope A, producer B, residence B, first wave C):
1. This wave is quick fix only. No organize-imports, source action, refactor, function or struct stub, code lens, or server command.
2. The server does not write files. The client applies the edit.
3. Each repair names the stable diagnostic code, the primary span of that diagnostic, and exactly one local text edit. The LSP must not keep a code-to-edit table and must not read the diagnostic message to build the edit.
4. The repair is computed on `textDocument/codeAction` from the current document analysis. It is not a required field of compiler `Diagnostic`, and it is not published inside `publishDiagnostics`, including `data`.
5. `publishDiagnostics` carries the stable compiler code on `Diagnostic.code` so the client can echo it. Source, severity, message, and related information stay as they were. Those presentation questions remain with `AGD-0054`.
6. A repair is returned only when the request context contains a diagnostic with the same code and the same primary range. An empty diagnostic list returns an empty action list. An `only` filter that does not include quick fix returns an empty action list.
7. Each item is a QuickFix `CodeAction`, not a `Command`. The edit touches one file, the requested physical document, and contains one `TextEdit`. There is no lazy resolve.
8. A path that is not a compiler-known regular file, including `/virtual/stdlib`, gets no edit.
9. If the frontend does not expose the capability, the server does not advertise `codeActionProvider`. A request that arrives anyway returns an empty list, not a protocol error. Absence of a fix is not a refused cursor.
10. PBS exposes the capability. Another frontend does not gain it merely by having a language service.
11. The first wave is two shapes, not three diagnostic codes.
- For every extra reserved attribute the declaration validator already reports as `E_SEM_DUPLICATE_RESERVED_ATTRIBUTE`, delete exactly that occurrence's span. Do not delete the first occurrence, the declaration, or neighboring whitespace.
- For an `InitAllowed` attribute with a non-empty argument list on a host signature, the shape the validator reports as `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` when the file is an interface module, replace that attribute span with `[InitAllowed]`. Do not emit that repair for any other attribute that shares the code. `[InitAllowed()]` is not diagnosed today and gets no repair.
12. Nothing else gets a quick fix in this wave. In particular: inserting `[Doc(markdown = """""")]` or any other Doc rewrite, inserting an empty or incomplete `[Host]` or `[BuiltinType]`, `W_SEM_IGNORED_VALUE`, unresolved imports, an invalid reserved-attribute target, parse errors, unresolved overloads, and method stubs.
`AGD-0048` still owns formatting. `AGD-0049` still owns import assistance and organize-imports. `AGD-0054` still owns range, related locations, and diagnostic presentation. The PBS diagnostics spec does not gain a mandatory remediation field.
Spec 23 §8.3 now states the shared contract: code actions are quick fixes only; the frontend produces each repair from the document syntax; tooling transports it and does not parse the message or switch on codes; the published diagnostic carries the stable code; a repair is returned only for a matching context diagnostic; the edit is one physical file; the server does not write files, return a command, or require resolve; a missing capability is an empty list, not an error; virtual documents get no edit.
## Final Implementation
| Layer | What landed |
|---|---|
| PBS repairs | `PbsQuickFixCollector` walks the same attribute surfaces as `PbsDeclarationSemanticsValidator`, including the interface-module gate. Duplicate reserved attributes become an empty replacement of the extra span. The first `InitAllowed` with arguments on an interface host signature becomes `[InitAllowed]`. |
| Source kind | `PbsSemanticReadSurface.sourceKindByFile` records the kind used to parse each file. A missing kind means project rules, so a project `declare host` does not pretend the validator emitted the interface-only `InitAllowed` diagnostic. |
| Generic contract | `FrontendLanguageService.codeActionsSupported` defaults false. `codeActions` defaults empty. `FrontendCodeAction` is title, diagnostic code, path, offsets, and `newText`. Empty `newText` is a deletion and is allowed. |
| PBS mapping | `PBSFrontendLanguageService` exposes the capability and returns repairs only for the requested regular file. `/virtual/stdlib` fails `Files.isRegularFile` and produces nothing. |
| LSP | `BaselineDocumentIssue.code` is copied onto `Diagnostic.code`. `data` stays unset. The bridge drops repairs whose code and range do not match a context diagnostic. `PrometeuTextDocumentService.codeAction` honors the quick-fix `only` filter and never fails the request for “no fix”. |
| Protocol | `codeActionProvider` is `CodeActionOptions` with kind `quickfix` and `resolveProvider` false, and only when the frontend reports support. Mapped actions are `CodeAction` values with a `WorkspaceEdit`. They are not `Command`s. |
Titles are `Remove duplicate reserved attribute` and `Remove InitAllowed arguments`.
## Examples
Duplicate `Doc` on a project file. The first copy stays. Each later copy is deleted at its own span:
```pbs
[Doc(markdown = """
First.
""")]
[Doc(markdown = """
Second.
""")]
fn duplicated() -> void { return; }
```
The quick fix removes the second attribute and leaves `First.`. A context diagnostic with the same range but code `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` produces no action. An empty diagnostic list produces no action.
Malformed or empty Doc is visible and not repairable here:
```pbs
[Doc(text = """
Wrong argument.
""")]
fn malformed() -> void { return; }
```
`InitAllowed` with arguments is repaired only on an interface-module host signature:
```pbs
declare host Gfx {
[Host(module = "gfx2d", name = "clear", version = 1)]
[InitAllowed(flag = 1)]
fn clear() -> void;
[Host(module = "gfx2d", name = "fill", version = 1)]
[InitAllowed()]
fn fill() -> void;
}
```
`clear` becomes `[InitAllowed]`. `fill` is already valid to the validator, so `[InitAllowed()]` is left alone. The same `InitAllowed(flag = 1)` inside a project file does not get that repair, because the validator does not emit the malformed-attribute diagnostic there.
The same collector deletes the extra copy of `BuiltinType`, `IntrinsicCall`, `BuiltinConst`, `Host`, and `AssetLowering` when the validator reports `E_SEM_DUPLICATE_RESERVED_ATTRIBUTE` for that surface. A malformed `Host` that merely shares the malformed-attribute code gets no edit.
## Pitfalls
Do not choose the edit in `prometeu-lsp` by switching on `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` or by parsing the English message. The code is too coarse, and the message is not the identity.
Do not store the repair on compiler `Diagnostic` or in `Diagnostic.data`. Compilation and quick fix stay different surfaces. The published code exists so the client can echo it back.
Do not match on `Diagnostic.source` as if it were the long-term identity field. Today the bridge still copies the code into `source` for the existing presentation. The code-action match uses `Diagnostic.code`. `AGD-0054` may change `source` later.
Do not delete the first duplicate, and do not trim the whitespace around the deleted span. That cleanup is formatting and belongs to `AGD-0048`.
Do not insert `[Doc(markdown = """""")]`, an empty `[Host]`, or an empty `[BuiltinType]`. Those edits trade one diagnostic for another, or invent a declaration.
Do not treat `W_SEM_IGNORED_VALUE` as a source edit. Discard exists in lowering, not as PBS syntax.
Do not offer the `InitAllowed` rewrite for `[InitAllowed()]` or for a project file. The validator does not diagnose those shapes as “arguments not allowed”, so there is no diagnostic to attach.
Do not return a protocol error when there is no fix. Rename refuses a bad cursor with an error. Quick fix answers “nothing to do” with an empty list.
Do not advertise `codeActionProvider` for every frontend that has a language service. The default capability is unsupported.
Do not treat this lesson as closing formatting, import assistance, diagnostic presentation, snapshots, folding, document links, or hierarchy.
## References
- Agenda: `AGD-0047` (scope A, producer B, residence B, first wave C)
- Decision: `DEC-0057`
- Plan: `PLN-0136`
- Spec 23 §8.3 — optional code actions; frontend-owned repair; match by code and range; empty list when unsupported
- Spec: `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md` — wording is not identity; remediation stays outside the v1 diagnostic minimum
- `LSN-0056` — code actions are an optional editorial capability
- `LSN-0058` — generic `FrontendLanguageService` for the LSP
- `LSN-0067` — no new editorial SPI without a real consumer; PBS implements the existing language service
- Still open: `AGD-0048` formatting, `AGD-0049` import assistance, `AGD-0054` diagnostics UX, `AGD-0051` snapshots, `AGD-0056` hierarchy
@@ -0,0 +1,70 @@
---
id: LSN-0074
ticket: pbs-lsp-remaining-editor-surface
title: PBS remaining editor surface is frontend-owned and transported by the LSP
created: 2026-09-22
tags: [studio, lsp, vscode, compiler-pbs, editor]
---
# PBS remaining editor surface is frontend-owned and transported by the LSP
## Original Problem
Nine open LSP agendas still described formatting, imports, semantic tokens, snapshots, completion, folding, diagnostics, document links, and call hierarchy as if none of that surface existed. By the time those agendas were still open, the server already advertised hover, completion, signature help, definition, references, outline, workspace symbols, rename, quick fix, and full semantic tokens. Each request still rebuilt analysis. References and rename had already shipped without a snapshot cache. There was no diagnostic whose meaning was "this name is not imported."
Treating the nine agendas as nine decisions would have reimplemented finished work and locked stale premises.
## Consolidated Decision
`DEC-0058` retired that split. One plan, `PLN-0137`, landed seven steps. The frontend produces the editorial result. The LSP transports it and does not invent a second policy. A missing capability is not advertised and returns an empty list, not a protocol error.
The wave explicitly does not add a project snapshot cache, type hierarchy, `completionItem/resolve`, snippets, a ranking score, range or on-type formatting, organize imports, a missing-import quick fix, `relatedInformation`, or a new semantic-token key.
1. Published editor diagnostic `source` is the bound frontend `languageId`. For PBS that is `pbs`. `code` stays the stable compiler code. The code is not copied into `source`.
2. A document link covers only the span of a `ModuleRef` whose module assembly already resolved to a regular file. Virtual stdlib and unresolved modules produce no link.
3. Folding comes from recovered spans of the listed declarations, their bodies, parameter lists, and `Doc` text blocks. A brace, parenthesis, or text block the tree does not cover still folds, including an unmatched opener through the end of the text. Selection grows outward from identifier, to argument or parameter list, to block or `Doc` text block, to declaration.
4. Formatting is full-document only. It reprints the token stream, indents by four spaces where brace or parenthesis nesting changes, leaves `Doc` text-block interiors untouched, and does not reorder declarations or move comments off their line.
5. Semantic tokens keep `PBSSemanticTokenProvider` as the baseline. Hover resolution may replace an identifier token only when an existing `PbsSemanticKind` matches the symbol. Failure, a broken file, or a symbol with no existing key keeps the baseline token.
6. Completion inside a `ModuleRef` lists project and stdlib modules the current resolver can already name. Every other offset keeps the existing member or general completion. Items stay eager and `resolveProvider` stays false.
7. Call hierarchy walks `CallExpr` nodes for functions and methods. It does not use the references index. A cursor that is not on a callable is empty. Type hierarchy is not advertised.
## Final Implementation
`CompilerLanguageServiceBridge` reads `LspProjectContext.languageId` into `BaselineDocumentIssue.source`. Document links read the physical module map that module assembly already built; stdlib files under `/virtual/stdlib` are not regular files, so they are not links. Folding, selection, and formatting reparse the open buffer with the existing lexer and parser. They do not require a successful project analysis. The semantic-token overlay runs only when editorial context is available and otherwise returns the provider tokens, including when project discovery fails. Module completion labels are the project modules from that same physical map plus the modules `ResourceStdlibEnvironmentResolver` can already resolve. Call hierarchy collects function, method, and constructor declarations from the recovered AST and matches `CallExpr` callees by name and call shape.
Spec 23 §8.3 states each of these rules. The nine earlier agendas, `AGD-0048` through `AGD-0056`, were abandoned and are not normative.
## Examples
A project import `@app:a` that resolves to `src/a/source.pbs` is one document link on that module-reference span. `@sdk:log` is not, because the stdlib file is virtual.
```pbs
fn helper() -> int { return 1; }
fn main() -> int { return helper; }
```
The use of `helper` without a call is an identifier in the lexical pass. Hover resolves it as a function, so the overlay key is `pbs-function`. A local such as `value` has no existing key, so it stays `pbs-identifier`.
```pbs
fn helper() -> int { return 1; }
fn main() -> int { return helper(); }
```
Prepare on `main` returns that function. Outgoing calls include `helper`. Incoming calls of `helper` include `main`. A cursor on a struct name returns no item.
## Common Pitfalls
- Do not copy the diagnostic code into `source`. The editor then shows the code twice and loses the language id.
- Do not build document links to `/virtual/stdlib`. Definition already refuses that destination.
- Do not treat document symbols as folding ranges. Outline and folding are different payloads.
- Do not pretty-print from the AST. Comments and `Doc` text-block interiors are not fully modeled as trivia on the tree.
- Do not add `pbs-local`, `pbs-parameter`, or `pbs-field` in the overlay. Those symbols stay on the baseline token until a later decision adds the key.
- Do not implement call hierarchy by inverting the references index. A reference is a use of a name, not a call.
- Do not start a snapshot cache because a later feature feels slow. This wave deliberately kept request-local analysis.
## References
- `DEC-0058` and `PLN-0137`, removed by housekeeping after this lesson
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md` §8.3
- Earlier surface: `LSN-0068`, `LSN-0069`, `LSN-0070`, `LSN-0071`, `LSN-0072`, `LSN-0073`
- Abandoned agendas: `AGD-0048` through `AGD-0056`
@@ -0,0 +1,103 @@
---
id: LSN-0075
ticket: studio-core-javafx-decoupling
title: Studio Services Must Outlive the Current UI
created: 2026-09-25
tags: [studio, architecture, spring, spring-modulith, javafx, adapters]
---
## Context
Prometeu Studio began as a desktop application in which JavaFX controls, application workflows, provider integrations, background execution, and lifecycle management shared one Gradle module. A static `p.studio.Container` made these dependencies easy to reach, but it also made the visual adapter the practical center of the product. That shape could not support another consumer, such as a future agent adapter, without either driving the UI or duplicating Studio behavior.
The migration needed to preserve the existing Java product and its behavior while making JavaFX replaceable. It also needed to preserve the autonomy of compiler, LSP, runtime, and especially `p.packer`; separating Studio did not authorize absorbing those domains.
## Key Decisions
### Human and non-visual adapters consume the same Studio services
**What:** The Studio is physically divided into `prometeu-studio-api`, `prometeu-studio-core`, `prometeu-studio-ui-javafx`, and `prometeu-app`. JavaFX depends on the neutral API, Core implements application use cases, and the application module composes concrete adapters.
**Why:** The stable boundary is UI versus application services, not JavaFX versus a future web framework. A future agent can depend on the same API without moving application rules out of Core.
**Trade-offs:** More constructor parameters and explicit contracts are required. That cost is intentional: dependencies are visible, testable, and constrained by Gradle instead of hidden behind a global container.
### Spring is a composition mechanism, not a domain dependency
**What:** Spring Boot runs in non-web mode only in `prometeu-app`. Core objects remain constructor-injected POJOs. Spring Modulith verifies the six functional Core modules: project, session, assets, shipper, runtime, and execution.
**Why:** Spring provides deterministic construction and lifecycle without contaminating the public API or Core. Modulith supplies executable documentation and dependency checks while Gradle remains the physical classpath boundary.
**Trade-offs:** The application configuration is deliberately explicit. Broad component scanning and turning JavaFX controls into Spring singletons would recreate hidden ownership and lifecycle problems.
### Provider boundaries follow stability, not uniformity
**What:** Core uses a provider's public API directly when it is stable and neutral. It owns a narrow port when the available integration is static, concrete, lifecycle-oriented, or otherwise unsuitable for Core. Packer's stable API is consumed directly; compiler static access, LSP lifecycle, and runtime process integration are isolated behind consumer-owned gateways implemented in `prometeu-app`.
**Why:** Wrapping every dependency creates redundant abstractions, while importing concrete implementations leaks infrastructure into Core. The useful boundary depends on the provider contract.
**Trade-offs:** The integration matrix must be reviewed case by case. There is no universal rule that every provider receives a gateway.
### Long-running work is a neutral application contract
**What:** Build, pack, and execution expose `OperationHandle<R>` with identity, snapshots, completion, cancellation, updates, and typed results. The application owns the executor implementation; JavaFX only projects operation state and switches to the FX thread.
**Why:** Background work must be equally consumable by JavaFX and future adapters. An executor or JavaFX `Task` is an implementation detail, not an application contract.
**Trade-offs:** Cancellation races and terminal state transitions require explicit tests. In particular, stopping execution must cancel the outer execution handle before its nested preparation handle can complete it successfully.
## Patterns and Algorithms
The dependency pattern is:
```text
JavaFX adapter ---> Studio API <--- future adapters
^
|
Studio Core
^
|
Spring non-web composition
```
External providers remain outside the Core module graph. Stable public provider APIs may be direct Core dependencies; concrete adapters remain in the application module.
Operational failures that a caller can recover from are returned as typed results or diagnostics. For example, metadata writes convert I/O failures into `AssetMetadataWriteResult`. JavaFX renders that result and does not treat an unexpected exception message or stack trace as a functional contract.
The removal sequence for a service locator is also reusable:
1. establish architecture tests and final modules;
2. introduce neutral contracts and explicit factories;
3. move behavior slice by slice into constructor-injected services;
4. reduce static call sites to zero;
5. delete the static container and manual composition together;
6. remove the mixed legacy module;
7. run the full build, packaging, desktop smoke, and shutdown gate as one indivisible acceptance step.
## Pitfalls
- Renaming packages without changing Gradle dependencies does not create a replaceable frontend.
- Replacing `Container` with `ApplicationContext.getBean()` throughout the code is still a service locator. Context lookup belongs only at the explicit application bootstrap boundary.
- Registering every control or dialog as a Spring singleton gives Spring ownership of visual lifecycle and makes multiple windows or future adapters harder.
- A gateway that merely mirrors a stable provider API adds indirection without protection. Conversely, direct use of static or concrete provider entry points leaks infrastructure into Core.
- Moving Packer behavior into `p.studio.core.assets` would reverse domain ownership. Studio coordinates Packer; `p.packer` remains independently consumable.
- Returning raw exception messages to JavaFX turns implementation accidents into an unstable user-facing protocol. Expected failures need neutral results or diagnostics.
- Marking the migration complete after compilation alone misses packaging, restoration, real JavaFX interaction, cancellation, and shutdown leaks.
## Takeaways
- The durable product boundary is the Studio service surface, not the current frontend technology.
- Spring belongs in composition; Spring Modulith belongs in verification and documentation; neither belongs in the neutral API.
- Gradle modules enforce physical isolation, while functional Core modules express ownership and allowed dependencies.
- JavaFX is an equivalent adapter, not the owner of project, asset, build, runtime, or execution rules.
- `Container` removal is a completion criterion, not an optional cleanup step.
- A future agent module can now be added as another API consumer without revisiting this migration or coupling AI concerns to JavaFX.
## References
- Decision: `DEC-0059` — Separate Studio Core from JavaFX with Spring Boot non-web and Spring Modulith.
- Plan: `PLN-0138` — Complete Studio Core and JavaFX Boundary Migration.
- Studio architecture: `docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md`.
- Studio specifications: `docs/specs/studio/README.md`.
- Packer boundary: `docs/specs/packer/1. Domain and Artifact Boundary Specification.md`.
- Packer integration: `docs/specs/packer/5. Diagnostics, Operations, and Studio Integration Specification.md`.
@@ -0,0 +1,303 @@
---
id: LSN-0076
ticket: studio-headless-runtime-ai-first
title: AI-first Studio Through Shared Authority and Headless Evidence
created: 2026-09-29
tags: [studio, runtime, headless, ai, mcp, automation]
---
## Context
Owner: **studio**, with runtime preparation in `../runtime` and language-owned PBS
documentation/LSP integration. DSC-0068, accepted DEC-0060 and PLN-0139 delivered
28 ordered steps: runtime (01–07), DEV/shared services (08–14), MCP (15–21), and
real integration/acceptance (22–28). Those workflow identifiers are historical
references; maintained contracts live in the specs linked below.
The original headless host was an in-process runtime API. Studio's human Debug
was useful, but neither a public automation protocol nor a safe authority boundary
for another editor. The goal was an external coding agent able to learn PBS,
edit a game, build/run it, see its pixels and iterate while the developer watches.
A complete gameplay library or embedded AI chat was not a prerequisite.
## Key Decisions
### Separate ownership, not parallel implementations
The external coding client owns conversation, model/provider, native file edits
and budget. Studio owns project authority, build orchestration, process supervision
and the shared observation model. Runtime owns execution and framebuffer semantics.
The language frontend/SDK owns its references; the existing project LSP owns semantic
queries. DEV and MCP consume the same neutral services.
```text
External coding agent -- local MCP HTTP --> Studio API/Core <-- DEV (JavaFX)
|
compiler/packer + existing LSP
|
supervised runtime JSONL/stdio
|
canonical PNG + frame identity
```
The configured installation provides `prometeu headless --stdio`. UTF-8 JSONL is
versioned, bounded and protocol-only on stdout; logs belong on stderr. A process
contains one session, with no implicit conflicting-work queue. Handshake establishes
runtime/protocol versions, capabilities and effective limits. Human Debug keeps its
own host/protocol. API/Core do not depend on JavaFX, Spring, HTTP/MCP or wire DTOs.
This avoids a provider adapter inside Studio and avoids automating the human debugger
as the execution API. The deliberate cost is an explicit process boundary and
reconfiguration of the external client after Studio restarts.
### Connection, authority and operation receipts are different identities
Authentication to loopback `/mcp` permits discovery/context/reference reads, not
editing authority. A human grants a specific project in DEV; acquisition then
returns a task identity. Manual Debug and agent work exclude each other in services,
not only through disabled UI buttons. Waiting for acquisition already blocks
conflicting manual work. A disconnected client does not release the project.
An operation's `clientRequestId` deduplicates a build or advance within the task.
The same ID and parameters return the same operation; changing parameters fails.
Lookup recovers a lost receipt without replaying frames. These records are in-memory,
not a source journal or restart-recovery mechanism. Runtime wire correlation has
its own `requestId`; neither identity is a substitute for valid task authority.
### Return is a cleanup barrier
The sequence is: invalidate task authority → stop managed work/processes → refresh
open documents from saved files → enable manual control. A late result cannot publish
a new capture or restore authority. Closing only DEV does not end the task; closing
the project/app does. Reopening starts manual, never with recovered agent authority.
Compile errors, guest faults and runtime loss remain distinct outcomes. The first
two permit correction within the same task. Runtime loss requires explicit session
replacement, not replay. Forced cleanup reports infrastructure failure first; a
later explicit reclaim may acknowledge success only after the process tree is dead.
The adversarial gate exposed a real app-teardown gap: UI closure alone did not own
every project session. The project-session factory now tracks and closes sessions
before dependent executors/LSP are destroyed, attempts other sessions after a failure,
and rejects new opens once closure begins. Cancellation also tolerates a concurrent
writer/timer shutdown so that it cannot bypass cleanup waiting.
### Direct edits require truthful boundaries
The agent edits actual project files. No worktree, merge/apply stage, code rollback,
Git cleanliness gate or automatic commit is imposed. Studio offers save-all-and-grant
for its dirty buffers and refreshes from disk on return. External unsaved buffers,
concurrent native writes and Git discipline remain the developer's responsibility.
Revocation cannot stop an external process from writing files directly; the developer
must also stop that client. SDK/external libraries are readable, not editable by
the game task. Read-only semantic refactoring scopes are enforced by the adapter.
### Pixels are evidence; metadata explains which evidence
MCP returns the lossless canonical PNG as native image content, plus session/build,
logical frame, render FrameId, dimensions, stride and pixel format. DEV projects
the same capture, with an explicit stale label after edits/rebuild/session changes.
Logical frames and render frames are independent counters. Neither a hash nor a
desktop screenshot replaces framebuffer pixels. Captures do not travel through
temporary image files, and there is no continuous video requirement.
Default bounds are 600 frames/advance, 64 KiB/command, 32 MiB/response including
image/envelope, 5 s handshake, 60 s call, and 5 s cancel/shutdown grace. Oversized
requests fail rather than clamp. Deadlines supervise processes, not simulated time.
## Final Result and Acceptance Evidence
All 28 plan steps completed on the tested platform. Production exposes 17 MCP
tools, live DEV configuration-copy, shared task authority, existing LSP/build,
indexed offline language references and the supervised real Rust headless host.
There is no production fake, embedded agent/chat, generic MCP editor/shell or
provider-specific runtime behavior.
### Requirement-to-evidence map
| Requirement and steps | Evidence retained in code or acceptance record |
| --- | --- |
| Runtime contract, commands, limits, determinism; 01–07 | Runtime `automation_process.rs`, headless tests, published request/response schemas and packaged-installation smoke |
| Neutral architecture; 08, 14, 15, 27 | Studio specs 9–11; architecture/Modulith tests, 17 passing cases in final full rerun |
| Grant/revoke, symmetric locks, dirty-buffer handoff; 09–14 | `DefaultAutomationSessionTest`, Core execution/session tests, `DevDesktopTest`, `DevWorkspaceProjectionTest` |
| HTTP authentication/Origin/restart and real config; 16, 21 | `LocalMcpServerTest`, `McpContractTest`, `McpConnectionGuideTest`; packaged restart rejects prior credential |
| Manifest context, unknown languages/versions, indexed offline docs; 17–18 | `CompilerProjectKnowledgeTest`, `CompilerProjectLanguageCatalogTest`, `InstalledKnowledgeTest` |
| Saved-source LSP and dependency navigation; 19 | `AutomationLspQueriesTest`, including `externalDependencyNavigationIsReadableButRefactoringIsReadOnly`; SDK limitation remains explicit below |
| Task operations, lost receipts, deduplication; 20–21 | `McpTaskToolsTest`, Core operation tests; reconnect/duplicate advance in real desktop HTTP gate |
| Real supervision/build/corrective iterations; 22–23 | `HeadlessProcessSessionTest`, `HeadlessInstalledRuntimeTest`, `HeadlessTaskIntegrationTest` |
| Runtime/MCP/DEV pixel and identity parity; 24 | `HeadlessMcpDesktopTest` + independent `DirectHeadlessOracle`; compare every ImageView pixel, PNG bytes, metadata, reset/fresh-session/rebuild |
| Interruption/cleanup/Debug regression; 25 | Nine real HTTP/runtime/DEV tests, including crash, forced shutdown, app close, stale-result rejection and real manual Debug; controlled document participant makes refresh barrier observable |
| Real coding client and human confirmation; 26 | Codex CLI 0.158.0 run described below; developer confirmed DEV and manual Debug Play |
| Full regression and distribution; 27 | Commands/counts below; installed references and two extracted-ZIP application lifecycle cycles |
| Final propagation and handoff; 28 | This lesson, updated spec 11 delivery boundary, README troubleshooting, CLI validation and housekeeping |
### Real external-client example
The developer granted control in `../ai-first-smoke` and copied the descriptor.
Codex CLI 0.158.0 used a fresh ephemeral session, only the configured Studio MCP,
project-root workspace-write isolation and its approval-review mechanism. Default
noninteractive approval policy initially blocked acquisition before any edit; the
retry retained sandboxing and did not bypass the human grant. The configured default
model was used; this record does not assert an independently verified model identity.
Credentials stayed out of versioned files and reports.
The agent consulted language/SDK references, edited only `src/main.pbs`, queried
LSP, built/packed and consumed native MCP image blocks. It changed the bundled
16x16 orange rectangle to one-pixel/frame directional movement in a 480x270 frame,
with no idle movement, opposing directions canceled before clamping, and unchanged
colors. Both builds succeeded; diagnostics were empty; final guest fault was null.
The 77 MCP calls included rejected/recovered calls and 13 native image blocks.
| Scenario | Logical frame / FrameId | Client-reported observed position |
| --- | --- | --- |
| Idle for 10 frames | 10 / 9 | (0,32) |
| Right 20; down 20 | 30 / 29; 50 / 49 | (20,32); (20,52) |
| Left 10; up 10 | 60 / 59; 70 / 69 | (10,52); (10,42) |
| Horizontal then vertical opposites, 10 each | 80 / 79; 90 / 89 | (10,42), unchanged |
| Right + down, 500 | 590 / 589 | (464,254), intact at bottom-right |
| All directions, 10 | 600 / 599 | (464,254), unchanged at edge |
| Left + up, 500; idle 10 | 1100 / 1099; 1110 / 1109 | (0,0), intact at top-left |
Build ID: `da441f65-479b-4099-8b86-fe48c7750e76`; runtime session:
`aa089209ec22c9a07286e5b01e967a57`. Frame identities/statuses were checked in tool
evidence; positions are the coding client's visual observations, not an invented
independent pixel measurement. Step 24 separately supplies exhaustive pixel parity.
Release returned MANUAL, no headless host remained, and game edits were preserved.
The developer confirmed the DEV result and successfully played the game through
normal Debug afterward. No game commit was made automatically.
### Builds, commands and scope
Studio executable code was `e6a83c94`; acceptance/troubleshooting documentation
was committed as `4c3597a2`. Runtime is merged at `01fab56`, distribution 0.1.0,
protocol 1.0. Native acceptance was **macOS ARM64 only**; no other coding client,
operating system or native-installer matrix is claimed.
Studio final commands:
```sh
./gradlew test build :prometeu-app:installDist --max-workers=2 --console=plain
./gradlew test :prometeu-app:installedKnowledgeTest :prometeu-app:headlessProcessTest --rerun-tasks -PstudioRuntimeInstall=/absolute/path/to/runtime --max-workers=2 --console=plain
```
The forced rerun executed all 91 tasks: normal suite **803 passed, 15 pre-existing
disabled tests, zero failures/errors**; installed knowledge **1 passed**; real
headless integration **4 passed**. The disabled compiler classes were
`IRVMIntrinsicRegistryParityTest`, `BackendGateIIntegrationTest` and
`MainProjectPipelineIntegrationTest`; none was disabled for this delivery.
The earlier step 25 targeted run had **254 passing tests**, including 9 real
HTTP/runtime/DEV and 4 DEV/Debug desktop tests. These overlap the full suite and
must not be added together as unique tests.
The Studio ZIP was extracted outside the checkout. A test-only JavaFX probe loaded
only its distribution JARs, delegated to the real App init/start/stop, used isolated
preferences, and passed two shown-launcher/closed-listener cycles, credential
renewal and old-token rejection. It did not operate the developer's open window.
ZIP SHA-256: `256f80b25416c284dca58e5519fdde0be36e9a6a2a450cb58f9c453862188c8d`.
Runtime final commands (cwd `../runtime`, separate temporary Cargo target):
```sh
cargo test --workspace --offline --quiet
PROMETEU_PROTOCOL_TEST_INSTALL=/absolute/path/to/runtime cargo test -p prometeu-cli --offline --test automation_process -- --include-ignored
cargo test -p prometeu-host-desktop-winit --offline --lib -- --ignored
```
Workspace **678 passed**, with six opt-in tests ignored there; separate runs passed
all **13** process/protocol cases including the installed package, and all **5**
localhost Debug cases. Twelve process cases overlap the workspace result. The
runtime package was built during preparatory delivery; the final gate reused and
validated it rather than claiming a fresh distribution build. Installed headless
SHA-256: `24b74712397545ddd7f745daded859c12d19102f81c5b51bf46c202fb8d6b65d`.
## Deferred Findings — Return Here After Implementation
The user requested deferred investigation, not silent removal of these findings.
| Finding | Owner and next investigation |
| --- | --- |
| `Input.pad()` SDK definition returns no location | Investigated on 2026-09-29: editorial lookup succeeds, but the physical-file policy filters the virtual SDK source. A separate chained-call editorial limitation was reproduced; see below. No runtime defect or fix is claimed. |
| Oversized reference page produces generic `-32602` | Studio MCP: improve parameter-limit discoverability/error specificity; default pagination already works. |
| Concurrent capture/fault/state may return BUSY | Studio MCP/Core: review concurrency guidance and clarity. Sequential calls work; do not weaken accepted exclusivity implicitly. |
| Framebuffer dimensions were discovered from capture | Language/runtime documentation: improve discovery; this does not prove dimensions are absent from every reference. |
| JDK 25/Kotlin target-24 fallback, JavaFX module/native-access/Unsafe warnings | Build/desktop tooling: review supported toolchain alignment and startup options separately. Passing tests do not erase warnings. |
| UI automation helper required newer Node than 22.13.1 | Environment tooling, not Studio: upgrade only as separate authorized work; human DEV confirmation supplied acceptance. |
| macOS ARM64 + Codex is the validated matrix | Future interoperability/platform testing; no uniform Grok/Windows/Linux promise. |
`NO_FRAME_AVAILABLE` before the first completed frame and client permission prompts
are expected boundaries, not guest defects. The shutdown ownership/reclaim bugs
found during step 25 are fixed and tested, not outstanding issues.
### Follow-up Investigation: SDK Navigation and Chained Calls
Owner: `compiler/pbs`, with propagation to compiler tooling contracts and Studio/LSP
consumers. This diagnosis does not reopen the completed AI-first delivery or change
its accepted requirements.
On 2026-09-29, a temporary Java probe exercised `CompilerLanguageServiceBridge`
with a request-local PBS overlay on `test-projects/main/src/main.pbs`, using the
application runtime classpath. It compared raw PBS editorial locations, exported
frontend locations, final LSP definitions, and hover. No production source was
changed. The comparison included imports from `@sdk:input` and `@sdk:gfx`, a local
`helper()`, an explicitly typed `pad: InputPad`, and `button: InputButton`.
| Cursor target | Raw PBS locations | Frontend / LSP locations | Hover |
| --- | --- | --- | --- |
| Local `helper()` | 1 | 1 / 1 | Resolved |
| `pad` in `Input.pad()` | 1 | 0 / 0 | `pad() -> InputPad` |
| `left` in `pad.left()` | 1 | 0 / 0 | `left() -> InputButton` |
| `down` in `button.down()` | 1 | 0 / 0 | `down() -> bool` |
| `down` in `pad.left().down()` | 0 | 0 / 0 | No symbol information |
| `left` and `down` in `Input.pad().left().down()` | 0 each | 0 / 0 each | No symbol information |
| `clear` in `Gfx.clear(0)` | 1 | 0 / 0 | Resolved |
There are two separate causes:
1. **SDK destination policy, not failed lookup.** `InterfaceModuleLoader` registers
SDK declarations under `/virtual/stdlib/sdk/input/main.pbs` (and the corresponding
`gfx` path). The source handle can read the declaration text, but the path is not
a physical file. `PBSFrontendLanguageService.toFrontendLocation` explicitly
rejects it via `Files.isRegularFile`. The LSP bridge also reads destination text
from disk; removing the frontend check alone would not deliver a usable target.
This behavior follows Compiler Spec 23 §8.3 and the physical-file rule preserved
in `LSN-0068`, and already has an explicit `Gfx.clear()` regression assertion in
`CompilerLanguageServiceBridgeTest.definitionUsesEditorialLookupAndPhysicalStdlibFiles`.
2. **Chained-call editorial receiver resolution.**
`PbsEditorialSupportService.resolveReceiverTypeBeforeDot` uses
`resolveChainSegmentsEndingAt`, which walks identifier/dot chains, not a call
expression ending in `)`. Thus the receiver of `down` in `pad.left().down()` is
unknown before destination mapping even begins. An explicitly typed intermediate
`button` restores raw lookup and hover, while the virtual-source policy still
prevents navigation. This is an editorial limitation, not evidence that executing
the same expression fails.
Recommended follow-up, not an accepted implementation decision: address chained
receiver resolution in the PBS editorial layer, and separately decide how to expose
the exact SDK sources as navigable read-only files. A version-scoped physical source
cache is compatible with the existing destination policy; virtual-document support
would require an explicit contract revision. Neither approach should duplicate SDK
semantics in MCP, permit SDK edits, or point to an unrelated developer checkout.
## Pitfalls and Takeaways
- A successful HTTP fixture is not an external-agent acceptance test. Prove both.
- Tab disposal is not task disposal; application teardown must own hidden sessions.
- Never unlock before process termination and document refresh acknowledge completion.
- Do not replay an advance because a connection or receipt was lost.
- A matching hash/blank canvas is weak visual evidence. Compare actual pixels,
metadata and an input timeline that changes a known object.
- An empty SDK definition is a language limitation, not permission to edit SDK code.
- Packaging language knowledge is part of making an unfamiliar language usable by
agents; adding another hidden language configuration is not.
- Keep provider permissions separate from Studio authority. Neither bypasses the other.
- Preserve explicit platform/client/test exclusions and deferred findings at closure.
## References
- Historical accepted decision DEC-0060 and completed plan PLN-0139, DSC-0068.
- [Studio architecture](../../../docs/specs/studio/9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md).
- [DEV and authority contract](../../../docs/specs/studio/10.%20DEV%20and%20Automation%20Specification.md).
- [MCP tools and knowledge contract](../../../docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md).
- [Usage and troubleshooting](../../../README.md#external-coding-agents-mcp).
- Runtime-owned contract: `../runtime/docs/specs/runtime/11a-headless-automation-protocol.md`.
- Previous foundation: [Services must outlive UI](../DSC-0067-studio-core-javafx-decoupling/LSN-0075-studio-services-must-outlive-the-current-ui.md).
@@ -1,62 +0,0 @@
---
id: AGD-0045
ticket: pbs-lsp-workspace-symbols
title: PBS LSP Workspace Symbols
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, workspace-symbols]
---
## Pain
Domain owner: `studio/lsp`
VS Code cannot search PBS symbols across the workspace, so users cannot quickly jump to functions, services, structs, constants, or stdlib-exposed APIs by name.
## Context
Document-level editorial features exist, but the LSP does not announce workspaceSymbolProvider and the compiler pipeline does not expose a project-wide symbol index designed for editor queries.
## Open Questions
- [ ] Should workspace symbols include only project files or also imported stdlib and SDK surfaces?
- [ ] What symbol kinds and ranking should be returned for duplicate names or overloads?
- [ ] Should the symbol index be cached from analysis snapshots or rebuilt per request in the first implementation?
## Options
### Option A - Project source index only
- **Approach:** Index project-owned declarations from analysis snapshots and expose `workspace/symbol`.
- **Pro:** Clear ownership and physical locations.
- **Con:** Does not help users discover stdlib/SDK symbols.
- **Maintainability:** Strong as a first wave.
### Option B - Project plus stdlib index
- **Approach:** Include project declarations and imported stdlib/SDK surfaces in the workspace symbol result set.
- **Pro:** Better discovery, especially for new users.
- **Con:** Requires a navigation policy for stdlib source or virtual targets.
- **Maintainability:** Good if stdlib target handling is solved; awkward otherwise.
## Tradeoffs
Workspace symbols are partly navigation and partly discovery. Including stdlib too early can create broken jumps if target locations are not defined.
## Recommendation
Prefer Option A first, then add stdlib once definition has a target policy.
## Discussion
This should follow document symbols and the semantic location/index work.
## Resolution
Ainda em aberto.
## Next Step
Decide whether first-wave workspace search includes stdlib or project-only symbols.
@@ -1,62 +0,0 @@
---
id: AGD-0046
ticket: pbs-lsp-rename-symbol
title: PBS LSP Rename Symbol
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, rename]
---
## Pain
Domain owner: `studio/lsp`
PBS users cannot safely rename a symbol through the editor, so they must edit text manually and risk missing references or changing unrelated overloads and same-name declarations.
## Context
Rename requires the same semantic identity and reference machinery needed by definition/references, plus workspace edits and conflict detection. The current LSP does not announce renameProvider.
## Open Questions
- [ ] Which symbols should be renameable in the first wave, and which should be protected such as stdlib, generated, host, or builtin declarations?
- [ ] How should rename handle overloads, member methods, imports, and labels with the same text?
- [ ] What validation should run before returning a WorkspaceEdit?
## Options
### Option A - Local file rename
- **Approach:** Rename only references in the current file using local semantic resolution.
- **Pro:** Smaller blast radius and easier conflict handling.
- **Con:** Incomplete for imported symbols and project-wide APIs.
- **Maintainability:** Acceptable only if explicitly presented as limited.
### Option B - Workspace semantic rename
- **Approach:** Use a project-wide reference index and return a `WorkspaceEdit` for all usage and declaration sites.
- **Pro:** Matches user expectations for editor rename.
- **Con:** Requires reliable references, collision checks, and write-safety across files.
- **Maintainability:** Strong once references exist.
## Tradeoffs
Rename is high trust. A partial or text-based rename can corrupt code silently, so scope must be explicit and conservative.
## Recommendation
Prefer Option B after semantic references are implemented. If delivered earlier, ship only a clearly limited local rename.
## Discussion
Do not implement rename before definition/references are resolved.
## Resolution
Ainda em aberto.
## Next Step
Decide whether rename waits for workspace references or ships a limited local-only wave.
@@ -1,62 +0,0 @@
---
id: AGD-0047
ticket: pbs-lsp-code-actions
title: PBS LSP Code Actions and Quick Fixes
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, code-actions, quick-fix]
---
## Pain
Domain owner: `studio/lsp`
PBS diagnostics are visible, but users do not get actionable quick fixes for common compiler/editor problems, making simple repairs slower than necessary.
## Context
The LSP maps diagnostics but does not announce codeActionProvider. Compiler diagnostics already carry codes and ranges, but not every diagnostic has enough structured repair data to generate safe edits.
## Open Questions
- [ ] Which diagnostics should receive quick fixes first?
- [ ] Should code actions be produced from diagnostic codes only, or from structured compiler repair hints?
- [ ] How should imports, reserved attributes, missing methods, and invalid Doc shapes be prioritized?
## Options
### Option A - Diagnostic-code quick fixes
- **Approach:** Map known diagnostic codes to simple edits in the LSP layer.
- **Pro:** Fast for a small set of obvious repairs.
- **Con:** Couples fixes to diagnostic text/ranges and can become brittle.
- **Maintainability:** Moderate if limited to trivial edits.
### Option B - Compiler repair hints
- **Approach:** Extend diagnostics with structured repair metadata and let the LSP map hints to code actions.
- **Pro:** Keeps product logic close to compiler knowledge.
- **Con:** Requires a new diagnostic/repair contract.
- **Maintainability:** Strong for non-trivial fixes and future frontends.
## Tradeoffs
Quick fixes are only useful if safe. Simple code-based fixes can ship first, but imports and generated stubs need stronger compiler context.
## Recommendation
Prefer Option B as the target design, with Option A allowed only for a small bootstrap set of unambiguous repairs.
## Discussion
This should follow diagnostics UX and import assistance for the first high-value fixes.
## Resolution
Ainda em aberto.
## Next Step
Pick the first three diagnostic codes eligible for safe quick fixes.
@@ -1,62 +0,0 @@
---
id: AGD-0048
ticket: pbs-lsp-formatting
title: PBS LSP Formatting
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, formatting]
---
## Pain
Domain owner: `studio/lsp`
PBS formatting is not automated, so style drifts across files, especially around attributes, services, blocks, imports, and multi-line Doc text blocks.
## Context
The LSP does not announce documentFormattingProvider. PBS has a parser and AST, but formatting must preserve documentation text block content while normalizing surrounding syntax and indentation.
## Open Questions
- [ ] Should formatting be AST-based, token-based, or hybrid to preserve comments and text blocks?
- [ ] What canonical style should PBS use for attributes, braces, imports, params, and text blocks?
- [ ] Should the first wave support full document formatting only, or also range/on-type formatting?
## Options
### Option A - Token-preserving formatter
- **Approach:** Format from tokens and trivia, preserving comments and documentation text block contents.
- **Pro:** Safer for active editing and text blocks.
- **Con:** Harder to enforce deep structural layout.
- **Maintainability:** Good if PBS formatting remains mostly syntactic.
### Option B - AST pretty-printer
- **Approach:** Reprint code from the AST using canonical style rules.
- **Pro:** Produces consistent output.
- **Con:** Risks losing comments/trivia and cannot handle malformed files well.
- **Maintainability:** Strong only after AST/trivia ownership is explicit.
## Tradeoffs
Formatting must not damage `Doc` text blocks. That makes trivia preservation a first-class requirement rather than an implementation detail.
## Recommendation
Prefer Option A or a hybrid token/AST formatter. Avoid a pure AST pretty-printer until comments/trivia are modeled.
## Discussion
Formatter decision should define canonical style before implementation.
## Resolution
Ainda em aberto.
## Next Step
Decide PBS canonical formatting rules for attributes, braces, imports, params, and text blocks.
@@ -1,62 +0,0 @@
---
id: AGD-0049
ticket: pbs-lsp-import-assistance
title: PBS LSP Import Assistance
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, imports, completion]
---
## Pain
Domain owner: `studio/lsp`
PBS users do not get import-aware assistance, so discovering exported symbols and adding the right import from barrels, stdlib, or project modules remains manual.
## Context
Completion already exists for local/editorial contexts, and stdlib imports are understood by the compiler pipeline. The LSP does not yet provide auto-import completion, organize imports, or import quick fixes.
## Open Questions
- [ ] Should auto-import target project modules, stdlib modules, or both in the first wave?
- [ ] How should barrels and explicit module imports be ranked and rendered in completion?
- [ ] Should organize imports be a code action, source action, formatter responsibility, or separate feature?
## Options
### Option A - Import completion only
- **Approach:** Suggest symbols from known modules and include import detail, but do not edit imports automatically.
- **Pro:** Low risk and improves discovery.
- **Con:** Still leaves manual import edits.
- **Maintainability:** Good as a stepping stone.
### Option B - Auto-import and organize imports
- **Approach:** Completion/code actions insert missing imports and source actions sort/remove unused imports.
- **Pro:** Matches modern editor expectations.
- **Con:** Requires robust module export indexing and edit placement rules.
- **Maintainability:** Strong if built on a proper import graph.
## Tradeoffs
Auto-import depends on knowing canonical exports and choosing an edit location. Doing that ad hoc in completion would create formatting and duplicate import issues.
## Recommendation
Prefer Option B as the target, but start with import-aware suggestions plus a limited missing-import quick fix.
## Discussion
This should be coordinated with code actions and formatter.
## Resolution
Ainda em aberto.
## Next Step
Decide first-wave import sources: stdlib only, project modules only, or both.
@@ -1,62 +0,0 @@
---
id: AGD-0050
ticket: pbs-lsp-semantic-tokens-semantic-classification
title: PBS LSP Semantic Token Classification
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, semantic-tokens]
---
## Pain
Domain owner: `studio/lsp`
PBS semantic highlighting exists, but parts of the token classification can remain lexical or superficial, which limits visual accuracy for same-looking identifiers with different semantic roles.
## Context
The current LSP announces full semantic tokens and maps frontend semantic presentation to VS Code. The compiler has semantic read surfaces that can classify symbols more accurately than raw tokenization.
## Open Questions
- [ ] Which token categories must become semantic identity-based first?
- [ ] Should semantic tokens be produced from compiler semantic surfaces, parser AST, lexer tokens, or layered output?
- [ ] How should tokens behave in files with syntax or semantic errors during active editing?
## Options
### Option A - Lexical tokens with semantic overlays
- **Approach:** Keep lexer-based tokenization as baseline and overlay semantic categories where resolution succeeds.
- **Pro:** Stable during broken edits and incremental to improve.
- **Con:** Some unresolved identifiers remain visually generic.
- **Maintainability:** Strong because fallback behavior is explicit.
### Option B - Fully semantic token stream
- **Approach:** Generate all semantic tokens from compiler semantic surfaces.
- **Pro:** Maximum accuracy when analysis succeeds.
- **Con:** Highlighting may disappear or degrade sharply on incomplete code.
- **Maintainability:** Risky unless snapshot/error recovery is excellent.
## Tradeoffs
Highlighting must be resilient while the user is typing. A perfect semantic pass that fails on partial code is worse than a layered model.
## Recommendation
Prefer Option A: lexical baseline plus semantic overlays from resolved symbols.
## Discussion
This can proceed independently but benefits from LSP snapshot/cache work.
## Resolution
Ainda em aberto.
## Next Step
Choose semantic overlay categories for the first pass.
@@ -1,62 +0,0 @@
---
id: AGD-0051
ticket: pbs-lsp-performance-cache-and-snapshots
title: PBS LSP Performance Cache and Snapshots
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, performance, caching]
---
## Pain
Domain owner: `studio/lsp`
Several PBS LSP requests rebuild or reanalyze substantial project state, which can become slow or jittery as projects grow and as richer features are added.
## Context
The current bridge favors correctness and simplicity by invoking compiler pipeline analysis for diagnostics and editorial documents. A complete LSP needs snapshot caching, invalidation, cancellation, and predictable latency.
## Open Questions
- [ ] What is the canonical project/document snapshot boundary for LSP requests?
- [ ] Which requests can reuse semantic read surfaces safely across document changes?
- [ ] How should cancellation, stale responses, and background reanalysis be handled?
## Options
### Option A - Request-local analysis
- **Approach:** Keep each LSP request self-contained and rebuild analysis as needed.
- **Pro:** Simple, deterministic, and less stateful.
- **Con:** Latency grows with project size and feature richness.
- **Maintainability:** Good for correctness, weak for interactive performance.
### Option B - Project snapshot cache
- **Approach:** Maintain per-project analysis snapshots with document overlays, invalidation, and cancellation-aware request handling.
- **Pro:** Required for responsive definition, references, rename, and semantic tokens.
- **Con:** Introduces lifecycle complexity and stale-result risks.
- **Maintainability:** Strong if snapshot ownership and invalidation are explicit.
## Tradeoffs
A complete LSP needs shared state, but shared state must not leak stale analysis into edits. The decision is about the boundary, not just caching.
## Recommendation
Prefer Option B before implementing workspace-wide features like references and rename.
## Discussion
Define snapshot lifecycle, invalidation triggers, and cancellation policy.
## Resolution
Ainda em aberto.
## Next Step
Decide whether snapshot caching is a prerequisite for references/rename or can be staged later.
@@ -1,62 +0,0 @@
---
id: AGD-0052
ticket: pbs-lsp-completion-depth
title: PBS LSP Completion Depth
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, completion]
---
## Pain
Domain owner: `studio/lsp`
PBS completion works for core cases, but a complete daily-use experience needs ranking, resolve details, snippets, overload handling, context-aware suggestions, and richer documentation.
## Context
The current LSP announces completion with trigger character '.' and returns detail/documentation for resolved compiler candidates. It does not use resolveProvider, snippets, broad trigger contexts, or advanced ranking.
## Open Questions
- [ ] Which completion contexts should be supported first beyond member access?
- [ ] Should completion use resolveProvider for expensive documentation/details or return everything eagerly?
- [ ] How should overloads, snippets, imports, keywords, and stdlib candidates be ranked?
## Options
### Option A - Eager rich completion
- **Approach:** Return labels, details, docs, and snippets directly in every completion response.
- **Pro:** Simple client behavior and immediate docs.
- **Con:** Can become expensive for broad/global completion.
- **Maintainability:** Good while candidate sets remain small.
### Option B - Completion resolve provider
- **Approach:** Return lightweight candidates first and populate expensive docs/details through `completionItem/resolve`.
- **Pro:** Scales better for large candidate sets and import-aware suggestions.
- **Con:** Requires client/server resolve plumbing and stable candidate identities.
- **Maintainability:** Strong for a full LSP.
## Tradeoffs
The current eager model is fine for scoped completions, but global/import-aware completion may need resolve to avoid latency.
## Recommendation
Prefer a staged approach: keep eager for current contexts, design resolve before broad workspace/import completion.
## Discussion
Define completion contexts and ranking before adding snippets or resolve.
## Resolution
Ainda em aberto.
## Next Step
List first-wave completion contexts beyond member access.
@@ -1,62 +0,0 @@
---
id: AGD-0053
ticket: pbs-lsp-folding-and-selection-ranges
title: PBS LSP Folding and Selection Ranges
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, folding, selection-range]
---
## Pain
Domain owner: `studio/lsp`
PBS users do not get structural folding or smart selection ranges, so navigating and selecting nested functions, blocks, services, attributes, and Doc text blocks is more manual than it should be.
## Context
The parser knows syntactic spans for declarations and blocks. The LSP currently does not announce foldingRangeProvider or selectionRangeProvider.
## Open Questions
- [ ] Should folding ranges be computed from AST spans, token pairs, or a hybrid that handles malformed files?
- [ ] Which constructs should fold in the first wave: imports, declarations, blocks, attributes, text blocks, or all of them?
- [ ] What selection range hierarchy should VS Code expose for identifiers, calls, params, blocks, and declarations?
## Options
### Option A - Parser span ranges
- **Approach:** Use AST spans for declarations, blocks, parameter lists, and text blocks.
- **Pro:** Accurate for well-formed code and easy to map to LSP ranges.
- **Con:** Can degrade when parsing fails mid-file.
- **Maintainability:** Good because parser owns structure.
### Option B - Token pair scanning
- **Approach:** Compute ranges from brace/paren/text-block tokens without relying on full AST validity.
- **Pro:** More resilient during malformed edits.
- **Con:** Less semantically meaningful and can produce noisy ranges.
- **Maintainability:** Good only as fallback.
## Tradeoffs
Folding and selection should keep working while typing. AST ranges are higher quality, but token fallback may be needed for broken files.
## Recommendation
Prefer a hybrid: AST ranges first, token fallback for unmatched/incomplete constructs.
## Discussion
This is an editor UX feature with low semantic dependency and can be planned independently.
## Resolution
Ainda em aberto.
## Next Step
Decide first-wave foldable constructs and selection hierarchy.
@@ -1,62 +0,0 @@
---
id: AGD-0054
ticket: pbs-lsp-diagnostics-ux
title: PBS LSP Diagnostics UX
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, diagnostics, ux]
---
## Pain
Domain owner: `studio/lsp`
PBS diagnostics reach VS Code, but the editor experience can still be hard to act on when ranges, related information, severity, and phase context are too generic.
## Context
The LSP maps compiler diagnostics to LSP diagnostics. Compiler diagnostics include phase/code/message/range in several paths, but not all editor-friendly fields are consistently exposed.
## Open Questions
- [ ] Which diagnostics need better ranges or related information first?
- [ ] Should diagnostic source include compiler phase, frontend, or both?
- [ ] What structured diagnostic metadata is needed for future quick fixes without coupling UI to text messages?
## Options
### Option A - Mapper-only UX improvements
- **Approach:** Improve LSP diagnostic mapping using existing diagnostic fields.
- **Pro:** Quick improvements to source, severity, and display consistency.
- **Con:** Cannot add missing related spans or repair metadata that compiler diagnostics do not expose.
- **Maintainability:** Good for presentation-only changes.
### Option B - Structured diagnostic contract
- **Approach:** Extend compiler diagnostics with editor-facing metadata such as phase, related locations, stable quick-fix hints, and refined ranges.
- **Pro:** Enables better diagnostics and future code actions without parsing message text.
- **Con:** Requires compiler/core diagnostic API changes.
- **Maintainability:** Strong as the foundation for quick fixes and richer UX.
## Tradeoffs
Some improvements belong in the LSP mapper, but the most valuable changes require structured information at diagnostic creation time.
## Recommendation
Prefer Option B as the target, with mapper-only cleanup allowed for low-risk display fixes.
## Discussion
This agenda should inform code actions before quick fixes become broad.
## Resolution
Ainda em aberto.
## Next Step
Inventory high-frequency diagnostics and identify which need better ranges, related information, or repair hints.
@@ -1,62 +0,0 @@
---
id: AGD-0055
ticket: pbs-lsp-document-links
title: PBS LSP Document Links
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, document-links, imports]
---
## Pain
Domain owner: `studio/lsp`
PBS import/module references and asset-like surfaces are plain text in VS Code, so users cannot click through to imported modules or related project resources.
## Context
The compiler understands module references and project files. The LSP does not announce documentLinkProvider, and the VS Code extension delegates all language behavior to the server.
## Open Questions
- [ ] Which references should become document links first: imports, barrels, stdlib modules, assets/addressables, or docs?
- [ ] How should virtual or stdlib resources be represented as link targets?
- [ ] Should document links overlap with go-to-definition or remain a separate lightweight navigation feature?
## Options
### Option A - Import/module links only
- **Approach:** Expose `documentLink` for module references such as `@sdk:gfx` and barrel paths.
- **Pro:** Narrow, useful, and mostly aligned with existing module resolution.
- **Con:** Does not cover assets/addressables or documentation links.
- **Maintainability:** Strong first wave.
### Option B - General resource links
- **Approach:** Link imports, stdlib modules, assets, addressables, and possibly documentation/resource surfaces.
- **Pro:** Richer navigation across project resources.
- **Con:** Requires resource-specific target policy and may overlap with definition.
- **Maintainability:** Good only after resource ownership is defined.
## Tradeoffs
Document links should remain lightweight. If a link requires semantic identity and symbol resolution, it may belong in go-to-definition instead.
## Recommendation
Prefer Option A first: imports and module references only.
## Discussion
Coordinate stdlib target handling with go-to-definition.
## Resolution
Ainda em aberto.
## Next Step
Decide first-wave link targets and how stdlib/module URIs are represented.
@@ -1,62 +0,0 @@
---
id: AGD-0056
ticket: pbs-lsp-call-and-type-hierarchy
title: PBS LSP Call and Type Hierarchy
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, call-hierarchy, type-hierarchy]
---
## Pain
Domain owner: `studio/lsp`
PBS users cannot inspect call relationships or type/member relationships from the editor, which limits understanding of larger projects after basic navigation exists.
## Context
Call hierarchy and type hierarchy are advanced LSP features. They depend on reliable semantic identity, references, callsite classification, and type ownership surfaces, so they should probably follow definition/references rather than precede them.
## Open Questions
- [ ] Should call hierarchy and type hierarchy be one discussion or split after dependencies are clearer?
- [ ] Which relationships are valuable for PBS: function call graph, service method calls, struct methods, contract implementations, host/intrinsic calls, or all of them?
- [ ] What prerequisite symbol/reference infrastructure must be completed before this feature is safe to implement?
## Options
### Option A - Call hierarchy only
- **Approach:** Implement incoming/outgoing calls for functions and methods after callsite references are stable.
- **Pro:** Directly useful and builds on executable call resolution.
- **Con:** Does not cover type ownership, contracts, or implementations.
- **Maintainability:** Strong if based on the reference/callsite index.
### Option B - Split call hierarchy and type hierarchy
- **Approach:** Treat call graph and type/member/contract hierarchy as separate decisions and implementations.
- **Pro:** Avoids mixing two different semantic models.
- **Con:** Creates more workflow artifacts and sequencing work.
- **Maintainability:** Strong; each feature can evolve on its own contract.
## Tradeoffs
Call hierarchy and type hierarchy share LSP vocabulary but not the same compiler data. Coupling them too early would make the first implementation harder to reason about.
## Recommendation
Prefer Option B: split after this agenda confirms dependencies, likely implementing call hierarchy first.
## Discussion
This should wait until definition and references are complete.
## Resolution
Ainda em aberto.
## Next Step
Decide whether to split into two discussions before moving to decisions.
@@ -323,3 +323,36 @@ The current Studio direction is:
4. the compiler should use explicit abstractions such as `StdlibEnvironment` and `StdlibModuleResolver`,
5. stdlib interface modules are parsed with the normal PBS parser and validated in interface-module mode,
6. reserved attributes such as `[Host(...)]` are extracted as compile-time metadata for later lowering.
## 13. Installed Language and SDK Reference Bundle
The PBS frontend distribution MUST provide local, indexed documentation through
the frontend reference-provider contract. This packaging does not create a new
normative specification: the numbered PBS documents in their owner directory
remain authoritative, and the quickstart/example remain informative.
The build MUST generate the reference index from owner-maintained sources:
- this directory's numbered specifications and README quickstart;
- the frontend's example manifest, PBS source and barrel;
- the actual packaged SDK `.pbs` and `.barrel` files, including their documentation.
Generated copies MUST NOT be edited independently. SDK declarations MUST NOT be
rewritten to manufacture a documentation-only API. The index MUST contain stable
reference identities, titles, kinds, packaged-resource identities, content hashes
and applicable SDK major/target. The loader MUST reject missing/corrupted indexed
content instead of advertising unreadable references or consulting a checkout.
For the current distribution, SDK/example selection is Game / major 1. The general
PBS specifications remain available for other selections, but Game SDK 1 references
MUST NOT be presented as another SDK version or target. An absent SDK reference
set MUST be explicit to consumers.
Language, compiler, SDK and index-schema versions remain independent. General
specification references use an unknown release version when owner release
metadata is absent; SDK-associated references identify the installed SDK major.
Content hashes identify the packaged texts, not a semantic language release.
Conformance MUST include reading all indexed references from installed JARs outside
the repository and compiling the shipped example against the installed SDK. No
network access or source checkout may be required by that reference-read path.
@@ -2,6 +2,73 @@
This directory contains the normative PBS specification set.
## Installed Quickstart (Informative)
This guide and the numbered specifications are packaged with the PBS frontend.
They describe the installed distribution, not a promise of a numbered language
release. A spec's `Draft v1` status is not the compiler version or SDK version.
The project manifest selects the SDK major with `stdlib`; current packaged
Game SDK resources use major `1`. Unknown language/compiler versions remain
unknown in Studio's context.
For an external coding agent:
1. Request `studio_project_context` for the absolute root of the open project.
2. Read `pbs:quickstart`, `pbs:spec:3` (syntax), `pbs:spec:4` (static semantics)
and the relevant SDK reference IDs returned in that context. Continue pages
until `nextOffset` is null. References are IDs, not filesystem paths.
3. Inspect the project and its dependencies before changing source. Only edit
the project's editable scope, excluding read-only SDK/external libraries.
4. Use the installed LSP and compiler to check changes. When the corresponding
MCP tools are available, acquire project control after the developer's DEV
grant, then use the advertised language/build tools. Documentation reads do
not require that grant. Missing tools/capabilities must not be assumed.
5. Build and test small changes. Runtime execution also requires a compatible
configured runtime; reading references does not install one.
### Small Game Project
The installed example has three separately indexed files:
- `pbs:example:game:1:prometeu.json`: a Game manifest with `language: pbs`,
`stdlib: 1` (serialized as a string), and no external dependencies;
- `pbs:example:game:1:src/main.pbs`: `[Init]` and `[Frame]` functions drawing a
moving rectangle through `Gfx` and constructing colors through `Color`;
- `pbs:example:game:1:src/mod.barrel`: the module's public declarations.
Copy these reference texts to the corresponding paths only when creating that
example in your editable project. The example is compiled in the test suite;
it is not a complete game or a claim that every requested gameplay abstraction
already exists. If a project has no external dependencies, no registry is needed.
For dependencies, follow the installed compiler's manifest/registry requirements.
PBS source lives under `src` for the installed provider. Functions use `fn`,
typed parameters and `->` return types. `let` declares a local binding;
`declare global` declares persistent global state. Imports name exports and a
module address, for example `import { Gfx } from @sdk:gfx;`. A `mod.barrel`
describes a module's public surface. Read the syntax/static-semantics chapters
for exact rules rather than inferring compatibility with another language.
### SDK Navigation and Limits
`pbs:sdk:game:1:sdk/gfx/main.pbs` exposes the actual installed Gfx source,
including documentation comments and signatures. Its `mod.barrel` reference
defines exports. Equivalent references exist for `sdk/asset`, `sdk/composer`,
`sdk/input`, `sdk/log`, and `core/color`. Read those interfaces before calling
them. Game SDK 1 does not currently ship `audio` or `core/math` modules.
Ordinary game source uses public services such as `Gfx`; it must not manufacture
host bindings or mutate SDK declarations. Asset/composer workflows require their
real asset/scene data and runtime capabilities. Reference availability does not
guarantee those project resources exist. SDK or tooling limitations should be
reported for separate work, not patched in read-only dependencies.
The reference index is generated from these owner-maintained documents and the
frontend's SDK/example resources. The index schema revision is not a language
version. Source hashes bind texts to the installed bundle; no repository checkout
or network is needed to read them. The numbered specifications remain normative;
this onboarding section and example are explanatory, not a second specification.
## Purpose
Specs define the official PBS language/frontend contract.
@@ -278,8 +278,30 @@ When a frontend exposes find-references, each returned usage or declaration loca
When a frontend exposes document symbols or outline, the result MUST be the named declaration tree of the requested document. Presence, hierarchy, and ranges MUST come from that document's recovered syntax tree. Semantic success MUST NOT be required. Semantic enrichment MUST NOT drop a named declaration that the syntax tree still exposes. A missing syntax tree MUST produce an empty list. Document symbols MUST NOT be a workspace symbol index, folding ranges, or a navigation list of foreign files.
When a frontend exposes workspace symbols, the result MUST be a flat search of named declarations whose locations identify compiler-known physical source files of the current analysis. Presence, names, kinds, details, and ranges MUST come from the recovered syntax of those files. Semantic success MUST NOT be required. Semantic enrichment MUST NOT drop a named declaration that the syntax tree still exposes. A missing analysis surface MUST produce an empty list. The workspace-symbol request MUST NOT require an open text document. A declaration without a compiler-known physical file MUST be omitted. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability. Workspace symbols MUST NOT be a document outline, folding ranges, a persistent symbol index, or a navigation list of virtual locations.
When a frontend exposes rename, the result MUST be a validated workspace edit of identifier spans whose locations identify compiler-known physical source files. Identity MUST be the physical declaration locations that definition returns at the cursor. A local or parameter name span MUST still be renameable when definition at that offset is empty. Each rewritten location MUST identify a compiler-known physical source file. A cursor that is not renameable, including builtins, virtual paths, unresolved names, keywords, comments, strings, import aliases and uses of those aliases, error case labels without their own span, and barrel files, MUST produce a protocol error or a null prepareRename result. Tooling MUST NOT return a successful empty workspace edit for a refused cursor or an invalid new name. The new name MUST be a language identifier that is not a keyword and MUST NOT collide in the same binding space, ignoring the sites being rewritten and the overload set being renamed. The server MUST NOT write files and MUST NOT rename file paths. Host prepareRename MUST advertise a prepareProvider when rename is exposed. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability.
When a frontend exposes code actions, the result MUST be quick fixes only: one workspace edit tied to a diagnostic of the requested physical document. The frontend MUST produce each repair from that document's syntax. Each repair MUST name the stable diagnostic code, the primary span, and exactly one local text edit. Tooling MUST transport that repair. Tooling MUST NOT choose the edit by parsing the diagnostic message or by a diagnostic-code table. A repair MUST NOT be a required field of compiler diagnostics and MUST NOT be published inside diagnostic data. The published diagnostic MUST carry the stable code so a later code-action request can match it. A repair MUST be returned only when the request context contains a diagnostic with the same code and the same primary range. An empty diagnostic context MUST produce an empty list. The edit MUST change only the requested physical source file. The server MUST NOT write files, MUST NOT return a command, and MUST NOT require a resolve round trip. A missing code-action capability MUST NOT advertise code actions and MUST produce an empty list rather than a protocol error. Virtual, untitled, or synthetic documents MUST NOT receive an edit. Code actions MUST NOT include organize-imports, source actions, refactors, or generated stubs unless a future accepted decision says so.
Compiler diagnostics and editor diagnostics are distinct ownership surfaces. Diagnostics returned by `analyze`, `compile`, and `build` are compiler contract output. Editor diagnostics MAY reuse compiler analysis results, live overlays, caches, or cancellation-aware tooling state, but a frontend MUST NOT be required to provide editor diagnostics in order to compile.
When tooling publishes an editor diagnostic, `source` MUST be the `languageId` of the bound frontend project. `code` MUST be the stable compiler diagnostic code when one exists, and MUST be empty when the compiler diagnostic has none. Tooling MUST NOT copy that code into `source`. Tooling MUST NOT publish related locations, compiler phase, or a repair payload on the editor diagnostic.
When a frontend exposes document links, each link MUST cover the span of a module reference whose resolved destination is a compiler-known regular file. A module reference that does not resolve to a regular file MUST produce no link. Tooling MUST NOT target virtual, untitled, or synthetic URIs, including virtual stdlib documents. Document links MUST NOT replace definition. A missing document-link capability MUST NOT be advertised and MUST produce an empty list rather than a protocol error.
When a frontend exposes folding ranges, the ranges MUST come from recovered syntax spans for top-level `fn`, `struct`, `service`, `contract`, `enum`, `error`, `callback`, and `host` declarations, their bodies, and `Doc` text blocks. A parameter list MUST fold from the parenthesis pair. A brace, parenthesis, or text-block delimiter that the recovered tree does not cover MUST still produce a token range, including an unmatched opener through the end of the text. Folding ranges MUST NOT be document symbols.
When a frontend exposes selection ranges, the chain at a cursor MUST run from the inside outward in this order: identifier, argument or parameter list, block or `Doc` text block, declaration. A layer that does not contain the cursor MUST be omitted. A missing folding or selection capability MUST NOT be advertised and MUST produce an empty list rather than a protocol error.
When a frontend exposes call hierarchy, incoming and outgoing calls MUST be callsites found by walking call expressions in the syntax tree. The references index MUST NOT be used as the call graph. A cursor that is not on a function, method, or constructor MUST produce an empty prepare result. Type hierarchy MUST NOT be advertised. A missing call-hierarchy capability MUST NOT be advertised and MUST produce an empty list rather than a protocol error.
When a frontend exposes completion inside a module reference, the candidates MUST be project and stdlib modules the current module resolver can already name. Completion outside a module reference MUST keep its existing member and general candidates. Completion items MUST stay eager. `resolveProvider` MUST stay false. Snippets and a new ranking score MUST NOT be added.
When a frontend exposes semantic tokens, the lexical token provider remains the baseline. An identifier token MAY be replaced with an existing semantic key when the same resolution used by hover names that symbol and an existing key matches it. Resolution failure, a broken file, or a symbol with no existing key MUST keep the baseline token. This overlay MUST NOT add a semantic-token key.
When a frontend exposes formatting, it MUST be full-document formatting only. Range formatting and on-type formatting MUST NOT be advertised. The formatter MUST reprint the existing token stream. It MUST NOT reorder declarations, join lines, or split lines. Indentation MUST be four spaces and MUST change only where brace or parenthesis nesting changes. The interior of a `Doc` text block MUST be copied unchanged. A comment MUST stay on the line of the token it already follows. A missing formatting capability MUST NOT be advertised and MUST produce an empty edit list rather than a protocol error.
`FrontendSpec` remains the source of static frontend-owned presentation metadata such as semantic vocabularies, host projections, and visual themes. Producing semantic tokens for a live document is an optional editor-facing capability; the existence of static presentation metadata MUST NOT imply that every frontend can provide live semantic-token results.
The frontend registry MUST resolve providers by `languageId`. A lookup for an unknown `languageId` MUST fail explicitly with a diagnostic-friendly error. Unknown languages MUST NOT silently fall back to PBS or to any other frontend.
@@ -25,6 +25,9 @@ Runtime-side reading semantics for `assets.pa` are defined upstream in `../runti
5. A future shipper is a consumer of packer artifacts, not a co-author of the asset contract.
6. Runtime reading semantics are not redefined by the packer.
7. The packer must stop at artifact publication, not cartridge assembly.
8. The packer's Java package root is `p.packer`; it must not be moved under `p.studio` or treated as a Studio subdomain.
9. The packer must remain independently consumable by Studio, command-line tooling, build tooling, and future automation adapters.
10. No Packer module may depend on `p.studio`, Studio UI, or Studio application modules.
## Packer-Owned Artifacts
@@ -57,6 +60,18 @@ Rules:
- shipper-specific workflow detail is deferred;
- published artifact names and meanings must remain documented and stable enough for later consumption.
## Studio Consumption Boundary
Studio is a consumer of Packer capabilities, not the owner of Packer semantics.
Rules:
- Studio should consume a stable, neutral, use-case-oriented public Packer API directly;
- Studio must not add a gateway that merely mirrors an already suitable public Packer API;
- when only concrete, static, infrastructure-oriented, unstable, or excessively broad integration is available, the Studio consumer may define a narrow consumer-owned gateway;
- implementations of Studio-owned gateways must stay outside Packer and outside the Studio Core functional contract;
- Studio projections and orchestration must not duplicate Packer validation, packing, diagnostic, concurrency, or artifact semantics.
## Non-Goals
- cartridge assembly flow
@@ -60,10 +60,24 @@ When the packer is embedded inside another host such as Studio, the host must bo
Rules:
- the embedded packer runtime must receive a typed event bus reference from the host when shared host visibility is part of the integration contract;
- the embedded packer runtime must receive a typed event sink or adapter from the host when shared host visibility is part of the integration contract;
- that reference is the baseline path for packer publish/subscribe integration in the embedded host;
- the embedded packer runtime must not quietly create a disconnected parallel event system when host integration expects shared operational visibility;
- in Studio, this shared typed event bus reference is owned by the Studio `Container`.
- in Studio, bootstrap, shutdown, and event adaptation are owned by the `prometeu-app` composition root;
- the embedded integration must not use `p.studio.Container`, Spring context lookup, or another static service locator.
### Studio Dependency Rule
The dependency direction is always Studio to Packer.
Rules:
- Studio Core may consume stable public contracts from `prometeu-packer-api` directly;
- a Studio-owned gateway is required only when an integration is concrete, static, infrastructure-oriented, unstable, excessively broad, or leaks provider lifecycle details;
- such a gateway must expose only the capabilities required by its consuming Studio module;
- gateway implementations and Packer bootstrap belong in `prometeu-app` or another explicit infrastructure adapter;
- the JavaFX adapter must consume neutral Studio API contracts and must not call Packer directly;
- Packer must not depend on `p.studio` and must not publish Studio UI events as part of its domain contract.
Baseline core services:
+4
View File
@@ -52,6 +52,10 @@ Specs should normally be fed by:
If a spec edit would require guessing an unresolved design choice, stop and surface the missing decision first.
## Integration Boundary
The Packer package root is `p.packer`, and Packer remains autonomous from Studio. Studio consumes stable public Packer APIs directly and introduces a narrow consumer-owned gateway only for concrete, static, unstable, or infrastructure-specific integration. Packer never depends on `p.studio`.
## Current Corpus
The current packer core corpus is:
@@ -6,7 +6,7 @@ Purpose: Define the normative shell structure of the Studio UI.
## Authority and Precedence
This specification consolidates the accepted Studio shell decision into normative form.
This specification consolidates the accepted Studio shell decision into normative form. DEC-0060 adds DEV and project-scoped automation authority; its detailed behavior is owned by the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md).
## Normative Inputs
@@ -46,10 +46,13 @@ The baseline workspace set includes:
- Asset Management;
- Debugger/Profiler;
- DEV, for granting/reclaiming project control and observing external-agent automation;
- Shipper, temporarily represented by the current `BuilderWorkspace`.
`BuilderWorkspace` is transitional and must not be treated as a long-term architectural reference for the final shipping surface.
DEV MUST remain separate from human Debug and MUST NOT offer chat or manual Play/input for the headless session. Selecting, hiding or switching away from DEV MUST NOT grant or release project authority. The shell's always-visible run surface remains visible, but conflicting manual actions MUST be unavailable while project control is ceded, including while waiting for an agent. Services MUST enforce the same exclusion; shell bindings alone are insufficient.
## Workspace Architecture Model
The shell-level workspace host exists to mount independently authored workspaces under one Studio contract.
@@ -57,11 +60,13 @@ The shell-level workspace host exists to mount independently authored workspaces
Baseline workspace architecture rules are:
- each workspace should have a composition root that mounts the workspace into the shell;
- the shell and workspace composition roots must receive neutral Studio API services through explicit constructor or factory injection;
- a workspace composition root should coordinate workspace services, state orchestration, and structural sync, but it should not own every local render path directly;
- project-session services that must survive workspace focus changes should be owned above individual workspace focus lifecycles and then consumed by workspace composition roots;
- event-observing workspace controls must be lifecycle-managed;
- workspace-local updates should flow through the Studio event system rather than ad hoc imperative redraw chains;
- future workspaces should consume shared Studio workspace framework primitives where those primitives already cover the needed behavior.
- shell and workspace code must not resolve application services through a static container or Spring application-context lookup.
The shell must not encourage a workspace model where every interaction falls back to whole-workspace refresh.
@@ -0,0 +1,392 @@
# 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;
- **Copy MCP configuration**, plus short connection/use instructions when the real MCP composition is available.
Actions MUST reflect shared service authority. DEV MUST NOT own a duplicate
lock or release authority when disposing visual subscriptions. Presentation
updates MUST follow the existing FX-thread, theme, localization and workspace
lifecycle rules.
DEV MUST NOT contain chat, provider settings, manual headless Play/input or
concurrent human control of the agent's execution. Human play/testing remains
in Debug with its existing host/protocol/lifecycle, subject to symmetric guards.
“Agent working” means the task has been acquired; it is not a claim to observe
all external edits, reasoning or conversation.
Without a real composed MCP endpoint, configuration copy MUST be unavailable
rather than produce a fabricated endpoint or token. Test doubles MAY supply
operations/captures to isolated tests, never masquerade as product execution.
## 6. Operations and Lost Responses
Automation MUST reuse the neutral operation executor/handle boundary: stable
operation identity, observable snapshots/progress, cancellation, asynchronous
completion and typed results. Build/pack diagnostics MUST be preserved.
Success, lifecycle termination, guest fault, infrastructure/host failure and
cancellation MUST remain distinguishable, including known partial progress.
Build and advance starts MUST return `operationId` promptly. Each start MUST
accept `clientRequestId` and allow authorized lookup by that identity if the
initial response is lost. Within the task:
- same identifier and same parameters MUST return the existing operation without reexecution;
- same identifier with different parameters MUST fail;
- deduplication and lookup MUST still validate project/task authority;
- the registry MUST stay in memory only, without restart recovery or replay.
Runtime `requestId` correlates a wire call; it is not Studio operation
deduplication. Neither transport error nor lost response authorizes blindly
retrying an advance. A runtime crash requires an explicit new session, not
restoration/replay; task authority remains governed by section 2.
## 7. Runtime Supervision and Canonical Capture
Studio MUST resolve `prometeu headless --stdio` from the configured runtime
installation. It MUST NOT discover/download another runtime over the network.
Missing or incompatible installations MUST fail explicitly. Each process owns
one session; each task MUST have at most one active headless session.
The gateway MUST validate the runtime's protocol major/minor, real version,
required capabilities and effective limits. Incompatible major or missing
mandatory capability MUST block the session; compatible minor additions are
permitted. It MUST obey complete UTF-8 JSONL framing and separate protocol
stdout from stderr diagnostics. Invalid input/schema MUST not disappear silently.
The 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 app MUST host Streamable HTTP at `127.0.0.1:<OS-assigned-port>/mcp` while
Studio is open. It MUST generate a random token per Studio start, require it
on connections, validate Origin and reject unexpected origins. No remote
binding, accounts, OAuth or stdio MCP bridge is part of this baseline.
Copied configuration MUST contain the actual endpoint/token and MUST NOT be
written to versioned files. Instructions MUST explain that restart requires
refreshing client configuration. Copying configuration and authenticating
MUST NOT grant control.
| Tool group | Required capabilities | Required authority |
| --- | --- | --- |
| Context/references | Project identity, languages, versions, capabilities and paginated references | Authenticated connection; no grant required |
| Control | Acquire task and release control | Prior human grant for acquisition; valid task identity for release |
| Language | Existing LSP diagnostics/navigation and supported capabilities | Valid project/task identity |
| Build | Compile and pack | Valid project/task identity |
| Headless | Boot/reset, input, advance, capture, state/fault and shutdown | Valid project/task identity |
| Operations | Query, lookup by client request identity and cancel | Valid project/task identity |
MCP capture responses MUST expose image content plus structured metadata;
clients MUST NOT need to parse logs or fetch a temporary file to obtain pixels.
Generic shell, generic file editing, Git, publication and out-of-project changes
MUST NOT be exposed as shortcuts around these specialized services. Studio
grant does not override the external client's own permission policy or require
a new human confirmation for every authorized Studio operation.
## 9. Project Language Context and References
The project manifest MUST be authoritative for primary language and dependencies;
there is no parallel AI-only language configuration. PBS is the project-creation
default, not a fallback for an unknown declared language. Installed compiler/LSP
integrations MUST advertise their actual capabilities; unknown versions or
capabilities MUST be reported as unknown, not invented.
Context MUST include:
- explicit project identity/root;
- language list and primary designation, with separately identified known language/compiler/SDK versions;
- source extensions/scope and actual LSP/build capabilities;
- references, examples, libraries and editable versus read-only roots.
A one-entry PBS list is valid; extensibility does not require another language
or a multilingual compiler. LSP MUST use the existing project server and support
project/library navigation through the diagnostics, definitions, references,
symbols and other queries/refactorings it actually supports. It MUST NOT
advertise nonexistent features or apply edits outside authorized scope.
The matching language/SDK distribution MUST ship indexed local quickstart,
syntax, semantics, examples and SDK reference material. Consultation MUST work
without Studio/compiler checkouts. MCP MUST read references by identifier with
pagination, not arbitrary paths. Documentation ownership remains with its
language/SDK/library owner; packaging does not create parallel language semantics.
Connection guidance MUST describe: connect → consult current project/languages/
references → acquire after human grant → work using saved files and validate
through LSP/build → release. The agent need not know PBS in advance. Missing
documentation or unsupported language MUST appear as explicit limitations;
static copied instructions MUST NOT substitute for current project context.
## 10. Delivery Phases and Conformance Gates
The accepted slicing is runtime → DEV/shared services → MCP → integration.
No intermediate phase constitutes complete delivery of this specification.
| Phase / plan steps | Required gate and limit |
| --- | --- |
| Runtime, 01–07 | Independent process client proves external contract, deterministic execution, canonical pixels, limits/failures and installed CLI; no Studio/AI dependency |
| DEV/shared services, 08–14 | Neutral authority/operations and document handoff first, then DEV; test grant/reclaim, Debug exclusion, dirty buffers, revocation/closure, late calls and FX lifecycle; desktop navigation smoke; doubles only in tests, no fake product endpoint |
| MCP, 15–21 | Automated MCP client proves authenticated discovery, real configuration, unauthorized rejection, exclusive acquisition, context/references, operations/deduplication, revocation and image contracts; no model required for this gate |
| Integration, 22–28 | Real runtime/LSP/build and an external coding client prove edit → build/pack → boot/input/advance → matching agent/DEV image → release; corrective loops and cleanup preserve manual Debug |
Cross-phase conformance MUST prove API/Core neutrality, the unchanged Modulith
dependency graph, application startup/shutdown, installed/offline references,
packaging and desktop behavior. Real-client tool/image compatibility MUST be
verified with the selected client, not promised uniformly across providers.
The vertical slice MAY use a simple existing PBS program; a complete game or
mature gameplay library is not a prerequisite.
### Decision Traceability
| Accepted requirement | Normative location |
| --- | --- |
| D1 architecture | Section 1 and spec 9 |
| D2 runtime; B1–B3 entry/wire/order | Sections 6–7 and runtime-owned protocol |
| D3 capture; B4 capture/limits | Sections 5 and 7 |
| D4 DEV/authority | Sections 2–5; shell spec and state-restoration exclusions |
| D5 files/LSP/write scope | Sections 3 and 9 |
| D6 MCP/operations; B5–B7 | Sections 6 and 8; spec 9's HTTP exception |
| D7 languages/onboarding; B8–B9 | Sections 8–9 |
| Ordered slicing and acceptance | Section 10 |
| Accepted exclusions | Section 11 |
## 11. Non-Goals
- Embedded agent, chat, provider adapter, provider credentials or cost/budget accounting.
- Mirroring external conversation, reasoning or all filesystem activity.
- Pixel-art generation, full-game libraries, audio capture or deep guest introspection.
- Shared editing, isolated worktrees, code snapshots/journals/checkpoints, merge/apply, divergence recovery, undo/rollback or automatic commits/clean-tree gates.
- Replacing compiler, Packer, LSP, VM or human Debug semantics; a new general-purpose Studio source editor.
- Remote MCP, accounts/OAuth, stdio MCP bridge, network runtime discovery or provider-specific connection wizard.
- Additional language implementation, persistent operation recovery or automatic task resumption.
- Integrated discussion-framework agendas/decisions/plans in the product; those are future work, not this runtime/DEV/MCP contract.
## Exit Criteria
Implementation is conformant only when all phase gates hold and:
1. Human grant, task acquisition, operation outcome and authority return are distinct and tested.
2. Service-level guards prevent conflicting manual work from grant through cleanup without blocking read-only navigation globally.
3. Save failure prevents grant; successful return refreshes documents without overwriting agent edits.
4. Revoke invalidates old calls first, works while waiting and preserves edits; project/application closure cleans owned processes and never restores authority.
5. DEV and the agent see the same canonical image with explicit build/session/frame correlation and stale labeling.
6. Local transport authentication does not bypass project/task authorization or scope restrictions.
7. Lost operation responses cannot duplicate execution; runtime crash cannot trigger replay or implicit authority release.
8. Language context and indexed local references reflect real installed support and work without source checkouts.
9. Manual Debug, architecture boundaries, packaging and real-client integration pass their regression gates.
@@ -0,0 +1,495 @@
# MCP Tools and Project Knowledge Contract
## Status, Scope and Authority
Owner: **studio**, application adapter and neutral automation API. This document
formalizes DEC-0060 B5–B9 and PLN-0139 steps 15–16. It complements
[DEV and Automation](10.%20DEV%20and%20Automation%20Specification.md), which owns
project authority, lifecycle, captures and phase gates. It does not change those
rules or the runtime-owned headless protocol.
The packaged machine-readable input schemas, authority classification and
examples are in `prometeu-app/src/main/resources/mcp/studio-tools-v1.json`.
Contract version is `1.0`. Catalog membership is not runtime availability:
`tools/list` MUST expose only composed handlers, never placeholder implementations.
Steps 17–21 connect the functional providers and DEV configuration assistance;
steps 22–28 provide the real runtime gateway and integrated acceptance.
## 1. Connection Contract
The app hosts `/mcp` on **127.0.0.1 with an OS-assigned port**, using the JSON
response form of MCP Streamable HTTP, protocol revision `2025-06-18`. The
initialization exchange negotiates that supported revision; no compatibility
with other revisions or deprecated HTTP+SSE transport is claimed. An offered
unsupported revision receives the supported revision in `InitializeResult`.
Each start generates a fresh 256-bit random bearer token. Every request MUST
include `Authorization: Bearer <token>`. Missing/wrong credentials return 401.
There is no query-string token, OAuth, cookie authentication, remote bind option,
stdio bridge or wildcard listener. The endpoint has no query parameters.
Native clients may omit `Origin`. If present, it MUST exactly equal the live
endpoint's origin (`http://127.0.0.1:<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. Explicit copying
for the external client is provided in step 21, not by logging startup secrets.
Initialization assigns a separate random `Mcp-Session-Id`. Subsequent requests
include this header and the negotiated `MCP-Protocol-Version`. The server can
recover the negotiated version from its connection session if the version header
is absent; an explicitly unsupported header returns 400. Missing required
session returns 400; an unknown/closed session returns 404. The client sends
`notifications/initialized` before tools. `ping` is available after initialization.
POST requires UTF-8 JSON and Accept support for `application/json` and
`text/event-stream`. Responses use JSON, not SSE. GET returns 405. DELETE closes
only the connection session, not project authority. Accepted notifications and
client responses return 202 without a body. Notification/disconnection alone
MUST NOT revoke a task or cancel an operation already returned by operationId.
The transport bounds incoming bodies to 1 MiB, sessions to 128 and request
handling to a bounded worker queue. Oversized bodies return 413; exhausted
session capacity returns 503. Stalled exchanges close after 15 seconds. These
are HTTP resource protections, **not** task expiration or guest/runtime timeouts.
Build/advance MUST return operation identities promptly. A lost response is
resolved by authorized lookup, not by assuming cancellation or replay.
These details follow the official MCP [transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports),
[lifecycle](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle)
and [tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools)
contracts. Optional SSE, server-initiated requests, sampling, prompts, resource
subscriptions and list-change notifications are not advertised.
### 1.1 DEV Connection Assistance
DEV displays the current endpoint without credentials and provides **Copy MCP
configuration** for an open project. The neutral `AgentConnectionGuide` supplies
availability and a deliberate clipboard export; JavaFX MUST NOT depend on the
HTTP server or keep credentials in labels, diagnostics, project state or history.
Connection lifecycle changes refresh availability. A closed project or stopped
server cannot export a descriptor. Unloading DEV only unsubscribes presentation
listeners; it does not stop the endpoint or revoke project authority.
The copied text is a provider-neutral JSON descriptor with `transport` set to
`streamable-http`, the live `url`, `headers.Authorization`, canonical `projectRoot`
and `instructions`. It is not a promise of a drop-in configuration format for
every external client. The developer maps URL/header fields to that client's MCP
configuration; a provider-specific wizard remains out of scope. The secret is
materialized only for explicit copying and MUST NOT be written to versioned files
or logs. Clipboard success/failure feedback MUST NOT repeat credential-bearing
content or raw exceptions. The clipboard itself is a deliberate secret export.
Copied instructions and MCP initialization guidance direct the client to discover
actual tools, read project context and applicable language/SDK/library references,
wait for human grant before acquisition, edit saved files within project scope,
validate with LSP/build, recover operation receipts by clientRequestId and release
explicitly. Missing language support is a reported limitation, not a PBS fallback.
They also explain that SDK/external libraries are read-only, revocation cannot
stop external file writes, copying grants no authority, and a Studio restart
requires fresh endpoint/token configuration. No provider or model is required
to test this guidance and the MCP service contract.
## 2. Identity and Admission
All tool inputs require `projectRoot`: an absolute filesystem root resolving to
an open project. UI focus never supplies it. Core services resolve the actual
project, including canonical-path/scope checks; syntactic validation does not
prove authorization.
The authority levels in the packaged catalog are:
- `authenticated`: connection authentication only; project/context/reference reads
are allowed before grant. No task token is returned by discovery.
- `granted`: acquisition validates the prior human grant and atomically creates
the sole task identity. The transport session ID is not that identity.
- `task`: `projectRoot` and `taskId` must identify the current acquired task.
Revalidate before admission, lookup and deduplication, including read-only LSP.
No MCP tool grants human permission or simulates pressing the DEV button.
There are no arbitrary-file read/write, shell, Git or publication tools. Editing
uses the external client's native tools within the context's editable scope.
## 3. v1 Tool Catalog
Fields below supplement `projectRoot`, and `taskId` where authority is `task`.
Input objects reject undeclared fields. IDs are nonempty opaque strings.
| Tool | Authority | Additional input | Successful value |
| --- | --- | --- | --- |
| `studio_project_context` | authenticated | none | Project context in section 5 |
| `studio_reference_read` | authenticated | referenceId; optional offset/limit | Indexed reference page |
| `studio_control_acquire` | granted | none | taskId, state=AGENT_WORKING |
| `studio_control_release` | task | none | state=MANUAL, only after ordered cleanup |
| `studio_language_query` | task | operation, parameters | Supported LSP query/proposal result |
| `studio_build_start` | task | clientRequestId | operationId, clientRequestId, state |
| `studio_headless_boot` | task | buildId | sessionId, buildId; boot uses the task's known build |
| `studio_headless_reset` | task | none | Current session/reset state |
| `studio_headless_set_input` | task | input | Current session acknowledgement |
| `studio_headless_clear_input` | task | none | Current session acknowledgement |
| `studio_headless_advance` | task | clientRequestId, frames | operationId, clientRequestId, state |
| `studio_headless_capture` | task | none | Canonical image and metadata in section 6 |
| `studio_headless_state` | task | none | Current session and runtime state |
| `studio_headless_fault` | task | none | fault object or null, preserving structural fault details |
| `studio_headless_shutdown` | task | none | Session shutdown acknowledgement after managed cleanup |
| `studio_operation_get` | task | exactly one of operationId/clientRequestId | State, known progress, typed result/failure |
| `studio_operation_cancel` | task | operationId | operationId, cancellationRequested |
Boot MUST NOT accept an arbitrary cartridge path. The shared service resolves
buildId to known project artifacts. Runtime limits/capabilities come from the
actual runtime, not fixed MCP promises. Frames is a nonnegative integer (zero
is valid); values beyond effective limits fail rather than being clamped.
Input is a replacement snapshot: booleans `up/down/left/right/a/b/x/y/l/r/start/
select/touch`, signed 32-bit `touchX/touchY`. Omitted fields reset to false/zero.
It preserves the runtime's normal sampling/edge semantics, not UI keyboard events.
Language queries use the capabilities returned by project context. Parameters
may contain URI, zero-based UTF-16 position/range/positions, workspace query,
newName, includeDeclaration or task-local itemId for multi-stage queries. The
provider MUST validate the parameters needed by the selected operation and reject
unsupported operations explicitly. Diagnostics, definitions, references and
symbols reuse the existing project LSP. Other queries/refactoring proposals are
exposed only when supported; returned edits MUST respect project versus read-only
SDK/library scope. No query applies filesystem edits.
### 3.1 Language Query Operations
`studio_language_query` uses the existing project's LSP server via a real client,
not a parallel language implementation or a direct call into compiler semantics.
Its successful value is `{operation, result, limitations}`. `result` is the JSON
projection of the existing LSP response (including null or an empty list when
appropriate); LSP union wrappers are unwrapped. Provider classes remain inside
the application adapter. Studio API/Core use maps, lists and scalar values only.
| Operation | Required parameters beyond projectRoot/taskId |
| --- | --- |
| `diagnostics`, `documentSymbols`, `documentLinks`, `foldingRanges`, `formatting`, `semanticTokens` | `parameters.uri` |
| `hover`, `completion`, `signatureHelp`, `definition`, `references`, `prepareRename`, `prepareCallHierarchy` | `uri`, `position`; references optionally accepts `includeDeclaration` |
| `rename` | `uri`, `position`, `newName` |
| `workspaceSymbols` | optional `query`; no document URI is needed |
| `selectionRanges` | `uri`, nonempty `positions` |
| `codeActions` | `uri`, ordered `range`; diagnostics are obtained from the current saved file |
| `incomingCalls`, `outgoingCalls` | task-local `itemId` from a hierarchy result |
Support MUST be checked against the running server's initialize response before
dispatch. Unknown operations, including currently unsupported type hierarchy,
return `UNSUPPORTED_CAPABILITY`. Context publishes the installed provider's
capabilities, including semantic tokens; hierarchy and rename preparations use
their corresponding server capability. Positions are zero-based UTF-16 offsets,
must fit the saved file and must not split surrogate pairs. Reversed ranges and
missing operation-specific parameters are rejected.
The application lifecycle supplies each open project's bound loopback LSP
endpoint. Studio uses OS-assigned ports so different open projects do not compete
for one fixed port. The public LSP configuration default remains unchanged for
other hosts. A manifest language change requires reopening that project's server;
the adapter MUST NOT send queries to a server bound to another language/root.
Each query uses a short-lived client connection. For document requests, the
adapter opens exactly the saved UTF-8 text and waits for that connection's
published diagnostics before issuing the semantic query. Other dependency files
are read from disk by the existing compiler bridge. A fresh connection prevents
reuse of stale overlays from previous requests or the human editor. Unsaved or
concurrent external writes remain the developer's responsibility.
Queries require the current task, share the project's work admission/cancellation
and DEV operation observation, and do not silently queue behind conflicting work.
Return/reclaim invalidates the task immediately, waits for worker termination,
then clears task-local hierarchy items before manual control is restored. Item
IDs from another task or project cannot be used. Client sockets/listeners close
on success, failure, timeout or cancellation; project-server shutdown closes its
accepted sockets and executor. A lost client does not independently grant control.
The adapter bounds connect time to 2 seconds and the LSP exchange to 10 seconds;
Core bounds the request worker wait to 12 seconds. Documents are limited to 4 MiB
of UTF-8 and task-local hierarchy state to 1024 items. These are adapter resource
guards, unrelated to the runtime's deterministic frame/watchdog semantics.
Document URIs must resolve to known physical project/dependency source files.
Symlink targets are canonicalized before admission. External sources may be
queried, but edit-producing queries on read-only roots are rejected. Every URI in
returned workspace-edit proposals is checked against the same editable/read-only
scope; an unsafe proposal is rejected as a whole. File-operation edits and
executable commands are not offered; `workspace/applyEdit` is always refused.
No query writes a file. Virtual SDK declarations may not have physical definition
locations in the existing LSP; indexed SDK references remain available instead.
## 4. Result, Error and Operation Contracts
Successful tools return `isError:false` with structuredContent
`{"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 require an AI grant. A session
is discoverable only after successful opening and until closure begins.
Unregistered/closed roots return `PROJECT_NOT_OPEN`.
Each call reads the saved `prometeu.json` and dependency manifests again. Missing
or invalid primary manifests fail explicitly instead of returning cached language
metadata. Languages are grouped by declared ID, with the primary flag derived
from the main manifest. Unknown IDs retain their identity and expose unsupported
build/LSP support; no default frontend is consulted.
Extensions and source roots come from the installed frontend specification.
LSP feature support comes from the same compiler bridge description used by the
existing LSP server, not from a duplicated PBS capability list. If that provider
cannot describe its LSP, support is UNKNOWN with an explicit limitation. These
are installed-provider capabilities, not a promise that the MCP language-query
tool is already composed or that any particular source file will compile.
Language versions remain unknown when no owner metadata exists. Compiler versions
use the installed frontend package's `Implementation-Version` only when present.
The requested SDK version has manifest provenance; the context distinguishes
versions supported by the installed provider from unsupported requests. Multiple
SDK requests for the same language yield an unknown aggregate version, an explicit
limitation and separate SDK library entries. These identifiers MUST NOT be
substituted for one another.
Dependency paths and registry entries use the compiler's existing resolver,
including its main-root-relative local path semantics and registry requirement.
Discovery does not create a registry, install dependencies or build sources.
Unresolved declarations remain visible with empty roots and limitations. Mixed
language graphs are described but reported as unsupported for the current build
pipeline. Discovery is bounded to 256 projects and 256 declarations per manifest.
The editable scope is the canonical project root **minus** read-only roots.
Read-only scope takes precedence: external/registry libraries and their transitive
dependencies remain protected even when stored beneath the project root or also
reachable through a local declaration. Source roots are canonicalized, including
symlink targets. SDK entries are always read-only; packaged SDK resources need not
have filesystem roots. Scope metadata does not sandbox an external agent's own
filesystem tools; the developer remains responsible for those tools and Git.
Paths in MCP results are absolute filesystem strings, not `file:` URIs.
### 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 a control grant or
task. It resolves the explicit open root and its current saved manifest selection
on every read. Changing SDK/target can invalidate previously advertised IDs.
Only IDs in that project's installed index can be read, including when other
languages/providers are installed globally. SDK and external-library texts remain
consultable, not editable through this surface.
Pagination counts Unicode code points: an astral character occupies one offset,
not two UTF-16 units. Offset 0/limit 4000 are defaults; limit MUST be 1–16000.
An offset equal to total returns empty text and null nextOffset. Offsets beyond
total, negative offsets, nonintegral values and integers beyond the implementation's
signed 32-bit range are invalid parameters, never wrapped/truncated to another page.
Missing or unreadable provider documentation yields `DOCUMENTATION_UNAVAILABLE`
limitations, not promised references. An uninstalled primary language yields
`UNSUPPORTED_LANGUAGE` for reference reads; an available index without the requested
ID yields `REFERENCE_NOT_FOUND`. Closed projects yield `PROJECT_NOT_OPEN` before
reference lookup. These failures do not grant/revoke task authority.
## 6. Image Contract
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.
DEV configuration-copy is connected as of step 21. The automated HTTP conformance
gate exercises all 17 tool contracts using real project knowledge/LSP and test-only
build/runtime ports; a separate HTTP test uses the real compiler/packer. This
completes MCP-phase conformance. 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. A probe of the installed SDK's `Input.pad()` definition returns
an empty result with the current language service; the gate does not claim SDK
symbol navigation where no location is returned. This is a language tooling
limitation, not a headless or MCP execution fallback.
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.
@@ -73,13 +73,14 @@ Propagation rules:
- propagation is workspace to global;
- global-to-workspace rebroadcast is not baseline behavior.
The global Studio bus is backed by a typed event bus reference owned by the Studio application container.
The global Studio bus is a JavaFX-adapter facility created by the application composition root and injected into the UI factory.
Container rules:
Composition rules:
- the Studio `Container` owns the global typed event bus reference used by `StudioEventBus`;
- host-integrated services that need shared Studio operational visibility should receive that container-owned typed event bus reference during bootstrap instead of allocating disconnected local buses;
- the `Container` must be initialized during Studio boot before packer-backed integration services, workspaces, or adapters begin use.
- `prometeu-app` owns construction and lifecycle of the shared UI bus;
- UI composition roots receive the bus explicitly and workspace buses derive from that injected instance;
- host integrations publish neutral application facts through their owning API boundary and may be adapted to UI events at the JavaFX edge;
- `p.studio.Container`, Spring context lookup, or another static service locator must not participate in event access.
This topology exists so callers do not need to duplicate publication decisions manually.
@@ -98,6 +99,8 @@ Illustrative baseline categories include:
- diagnostics update events;
- asset selection events.
Selection, navigation, attach/detach, edit scope, and presentation refresh are UI-local event categories. Application facts such as execution state, build results, runtime state, and asset operation results belong to neutral API contracts owned by their functional module and must not be defined only as JavaFX events.
For project bootstrap and splash/loading integration, the Studio event catalog should reserve typed events for:
- project loading started;
@@ -1,169 +1,66 @@
# Studio Components Module Specification
# Studio JavaFX Components Boundary Specification
Status: Draft
Scope: `prometeu-studio-components` role, admission policy, and JavaFX wrapping boundary
Purpose: Define the authoritative visual control layer for the Studio.
## Status
Active
## Applies To
- `prometeu-studio-ui-javafx`
- shared Studio controls and workspace-framework primitives
- JavaFX controls actively used by the Studio
## Purpose
Define the visual component boundary inside the JavaFX adapter without creating a second application or domain layer.
## Authority and Precedence
This specification consolidates the accepted Studio components module decision into normative form.
## Normative Inputs
- `prometeu-studio-components`
- Studio shell and workspace UI needs
- JavaFX controls actively used by the Studio
This specification is subordinate to [`9. Studio Core and Adapter Architecture Specification.md`](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md).
## Core Rules
1. `prometeu-studio-components` is the official visual control module for Studio UI.
2. Studio UI should normally consume visual controls from `prometeu-studio-components`, not directly from raw JavaFX.
3. A control enters the module when it is needed by the current Studio UI wave.
4. Controls in the module wrap and shape the JavaFX controls the Studio actively uses, but do not clone the full JavaFX API.
5. Every admitted control must preserve theme and i18n compatibility.
6. Reusable event-driven workspace controls should be admitted when they are part of the active Studio workspace framework.
1. Reusable Studio visual controls belong to `prometeu-studio-ui-javafx`.
2. The JavaFX adapter may organize reusable controls by shell, forms, banks, lifecycle, navigation, feedback, and inspection roles.
3. A control is admitted when it has an immediate Studio consumer; speculative mirroring of JavaFX is forbidden.
4. Shared controls must preserve theme, localization, and explicit visual-state behavior.
5. Controls that observe UI events must expose predictable attach/detach or subscribe/unsubscribe lifecycle behavior.
6. Visual controls must depend on neutral Studio API contracts, not core or provider implementations.
7. Domain rules, application orchestration, filesystem workflows, compiler/Packer/LSP/runtime calls, and Spring composition do not belong in the visual component layer.
## Module Role
## JavaFX Wrapping Boundary
`prometeu-studio-components` is:
The Studio may use raw JavaFX for trivial local composition. A reusable control should expose the Studio-facing API actually needed instead of cloning the complete upstream JavaFX surface.
- the authoritative Studio control layer;
- the home of the Studio visual dialect;
- the place where Studio-facing controls are shaped for Studio use;
- the preferred home for reusable lifecycle-aware workspace controls when those controls are part of the visible Studio UI dialect.
Shared controls may include:
`prometeu-studio-components` is not:
- shell and action controls;
- workspace rails and hosts;
- form sections and action bars;
- list, tree, inspector, and dual-list surfaces;
- activity, progress, badges, headers, and feedback controls;
- lifecycle-managed visual primitives.
- a speculative generic framework;
- a full reimplementation of JavaFX;
- a dumping ground for unrelated non-visual infrastructure.
## Construction and Lifecycle
## Admission Policy
Controls, rows, dialogs, and views MUST NOT be Spring singletons by default. A Spring-managed JavaFX composition factory may create them with explicit constructor dependencies.
A control is admissible when it is needed by the current Studio UI work.
Controls that attach event subscriptions MUST release them when detached. UI-local events may coordinate selection, navigation, editing scope, attach/detach, and presentation refresh. Request/response application behavior MUST use injected Studio API services directly.
Rules:
## State Boundary
- immediate current Studio use is sufficient justification;
- a second use is not required when the control is clearly part of the shell or the current workspace surface;
- no control should be added without an immediate Studio consumer.
- a control needed first by one workspace may still be admitted when it is clearly intended as a reusable Studio workspace primitive.
Presentation-only view models, form drafts, selection state, and formatting helpers may live beside JavaFX controls when they do not determine domain outcomes.
## Studio Usage Rule
The baseline Studio UI should not rely on raw JavaFX controls as its normal visual surface.
Rules:
- a visual control used by Studio should normally come from `prometeu-studio-components`;
- extremely trivial local composition may stay in `prometeu-studio`;
- local exceptions must remain exceptional rather than becoming the default path.
## Wrapping Boundary
Controls in `prometeu-studio-components` must wrap the JavaFX controls the Studio actively uses.
Rules:
- the Studio-layer control should expose the Studio-facing API actually needed;
- exhaustive mirroring of upstream JavaFX APIs is not required;
- the goal is consistency and clarity, not a perfect one-to-one mirror of every JavaFX type.
## Control Lifecycle Hooks
Studio controls may need to observe event buses or other external state.
Rules:
- the control layer must provide explicit subscribe and unsubscribe lifecycle methods that can be overridden when needed;
- the control layer should also provide `onAttached()` and `onDetached()` lifecycle hooks;
- `onAttached()` should call `subscribe()`;
- `onDetached()` should call `unsubscribe()`;
- controls that attach subscriptions must also define how those subscriptions are released;
- event-driven controls must not hide subscription lifecycle completely inside ad hoc local wiring.
These hooks exist so event-driven controls remain predictable and safe to embed in shell and workspace UI.
## Reusable Workspace Primitives
Some reusable controls are not shell-only and are not domain-specific either.
They may still belong in `prometeu-studio-components` when they are part of the visible Studio workspace framework.
Illustrative admissible examples include:
- projection hosts for list/tree/detail surfaces;
- lifecycle-managed row or item controls;
- reusable section or inspector surfaces;
- visible controls that encode local-patch versus structural-sync interaction patterns.
What does not belong here:
- workspace-specific orchestration logic;
- domain-specific service calls;
- hidden coordination code with no visible control responsibility.
## Typical Control Scope
Typical controls that belong in the module include:
- shell controls;
- action controls and buttons;
- tab systems;
- tree and list controls;
- inspector and panel surfaces;
- activity and feedback surfaces;
- badges, headers, and related Studio primitives.
What stays outside the module:
- workspace-specific composition logic;
- non-visual domain behavior;
- speculative controls with no immediate Studio consumer.
## Theme and i18n
Every admitted control must support:
- CSS-based theming;
- safe locale-aware text behavior when text is exposed;
- no hardcoded user-facing text;
- explicit visual states where state matters.
## Organization Guidance
The module should be organized by Studio role rather than vague technical buckets.
Illustrative areas include:
- shell;
- actions;
- navigation;
- feedback;
- inspection;
- trees.
## Anti-Bloat Rule
The module must remain:
- intentional;
- Studio-driven;
- small enough to reason about;
- broad enough to prevent UI entropy in the application.
Non-visual policies and workflows that determine asset validity, capacity, metadata, build, runtime, project, or semantic results MUST live behind `prometeu-studio-api` and be implemented by `prometeu-studio-core` or an explicit infrastructure adapter.
## Non-Goals
- defining the first concrete component set in full detail
- defining final package layout exhaustively
- mirroring the entire JavaFX control hierarchy
- storing domain-specific workspace orchestration code in the components module
- creating a standalone `prometeu-studio-components` Gradle module;
- wrapping the full JavaFX API;
- storing workspace business logic in controls;
- using Spring as a registry for each visual object;
- defining components for a future web UI.
## Exit Criteria
This specification is complete enough when:
- the module role is unambiguous;
- admission rules are stable enough to guide implementation;
- reusable workspace-control admission is clear enough to prevent local reimplementation drift;
- the JavaFX wrapping boundary is clear enough to prevent drift.
This specification is satisfied when reusable JavaFX controls have clear visual ownership, explicit lifecycle behavior, neutral injected dependencies, and no application or provider implementation responsibilities.
@@ -6,7 +6,10 @@ Active
## Applies To
- `prometeu-studio`
- `prometeu-studio-api`
- `prometeu-studio-core`
- `prometeu-studio-ui-javafx`
- `prometeu-app`
- the Studio `Assets` workspace
- packer-facing Studio service integration for asset browsing, inspection, diagnostics, and staged mutations
@@ -29,6 +32,7 @@ This specification extends:
- [`1. Studio Shell and Workspace Layout Specification.md`](1.%20Studio%20Shell%20and%20Workspace%20Layout%20Specification.md)
- [`2. Studio UI Foundations Specification.md`](2.%20Studio%20UI%20Foundations%20Specification.md)
- [`3. Studio Components Module Specification.md`](3.%20Studio%20Components%20Module%20Specification.md)
- [`9. Studio Core and Adapter Architecture Specification.md`](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md)
For packer-facing semantics, this specification must align with:
@@ -52,7 +56,7 @@ The workspace must assume:
- diagnostics, activity, progress, and staged mutation responses are available from Studio-facing services;
- packer-facing operational freshness may surface states such as `healthy`, `stale`, `diverged`, `reconciling`, or `failed`.
Packer-backed operational events consumed by this workspace are expected to enter Studio through the container-owned typed event bus path rather than through workspace-local ad hoc bus creation.
The JavaFX workspace must consume neutral Studio asset contracts. Stable public Packer APIs are consumed by Studio Core where appropriate; Packer bootstrap and concrete integration remain in `prometeu-app`. Packer-backed application facts may be projected into UI-local events at the JavaFX edge, but the workspace must not call Packer directly or create an ad hoc provider integration.
## Workspace Model
@@ -100,6 +104,7 @@ The `Assets` workspace must be implemented as a composition root plus lifecycle-
Rules:
- the workspace root should coordinate service calls, workspace state, and structural synchronization;
- service calls must target injected `prometeu-studio-api` contracts; domain workflows and filesystem orchestration must not be implemented by the workspace root;
- the workspace root should not own the render and update path of every navigator row, details section, and form control directly;
- the navigator host, asset rows, selected-asset details host, and details-internal sections/forms should subscribe only to the events and state they consume;
- event-consuming controls must subscribe only while mounted in the UI tree;
@@ -6,7 +6,10 @@ Active
## Applies To
- `prometeu-studio`
- `prometeu-studio-api`
- `prometeu-studio-core`
- `prometeu-studio-ui-javafx`
- `prometeu-app`
- Studio project-session persistence under `.studio/`
- project-local Studio session restoration state
- project-local Studio setup configuration
@@ -26,7 +29,7 @@ It extends:
## Core Rules
1. The canonical root for project-local Studio persistence MUST be `.studio/` in the project root.
2. The main project-local Studio session-restoration store MUST be owned by `StudioProjectSession`, or by a service explicitly owned by `StudioProjectSession`.
2. The main project-local Studio session-restoration store MUST be owned by the neutral project-session boundary, implemented in `p.studio.core.session` or by a project service explicitly composed into that session.
3. The main session-restoration store MUST remain a single file at `.studio/state.json`.
4. The main session-restoration store MUST be versioned.
5. The main session-restoration store MUST load when the project session opens.
@@ -76,6 +79,8 @@ The main session-restoration store MUST NOT include:
- heavy operational output;
- recomputable results that do not represent session restoration state.
Under DEC-0060, automation grants, task/control identities, active runtime sessions and the task-local operation/deduplication registry MUST NOT be persisted or restored through `.studio/state.json` or `.studio/setup.json`. Reopening a project MUST start under manual control. Restoring DEV as the selected workspace is presentation restoration, not permission to resume work. MCP connection credentials MUST NOT be stored in versioned files; they are regenerated on Studio restart. See the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md).
`Project-local activity` and project-local setup may still live under `.studio/`, but they are separate persistence concerns and not part of the main session-restoration store defined here.
## Ownership Rules
@@ -0,0 +1,180 @@
# Studio Core and Adapter Architecture Specification
## Status
Active
## Applies To
- `prometeu-studio-api`
- `prometeu-studio-core`
- `prometeu-studio-ui-javafx`
- `prometeu-app`
- integrations with compiler, Packer, LSP, and the runtime
## Purpose
Define the physical and functional boundary that makes the Studio consumable by interchangeable human and automation adapters without coupling application behavior to JavaFX, Spring, or a specific external provider.
## Authority and Precedence
This specification implements `DEC-0059` and the accepted `DEC-0060` AI-first baseline. It is the normative architecture reference for the Studio split. DEC-0060 adds shared automation services and the narrowly scoped local MCP server exception below; it does not replace the module boundaries or dependency direction.
The [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md) defines project authority, document handoff, operations, captures and delivery gates. More specific domain specs MUST preserve the dependency direction defined here. Normative requirements describe the target contract, not a claim that every delivery phase is already implemented.
## Architectural Model
The Studio is a set of project and tooling services consumed by adapters:
```text
JavaFX UI ──> Studio API <── local MCP adapter <── external coding agent
│
▼
Studio Core
▲
│
application/infrastructure adapters
```
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
1. `prometeu-studio-api` MUST contain toolkit-neutral contracts, commands, queries, DTOs, diagnostics, results, events, and operation contracts.
2. `prometeu-studio-core` MUST contain JavaFX-free application services, sessions, policies, orchestration, and Studio-owned use-case implementations.
3. `prometeu-studio-ui-javafx` MUST contain visual workspaces, controls, dialogs, bindings, navigation, presentation projections, theme application, localization binding, and JavaFX-thread dispatch.
4. `prometeu-app` MUST contain the desktop entry point, Spring composition, concrete integration adapters, lifecycle, and packaging.
Gradle is the physical classpath boundary. Spring Modulith verifies the functional modules rooted exclusively at `p.studio.core`; it does not replace the Gradle modules.
The legacy mixed `prometeu-studio` module and the static `p.studio.Container` service locator MUST NOT exist in the final architecture.
## API Neutrality
The public Studio API MUST be plain Java and MUST NOT depend on:
- JavaFX;
- Spring Framework, Spring Boot, or Spring Modulith;
- HTTP, AI, MCP, or provider SDKs;
- concrete runtime-wire or MCP transport DTOs;
- concrete compiler, Packer, LSP, or runtime implementations;
- `p.studio.core` or `p.studio.ui.javafx` internals.
Public contracts MUST NOT expose `Stage`, `Scene`, `Node`, JavaFX properties, controls, `Task`, `ApplicationContext`, Spring events, or provider-specific implementation types.
Expected failures MUST use domain status, diagnostics, and typed results. A universal `Result<T>` abstraction MUST NOT be introduced.
## Core Rules
Core classes MUST be POJOs with constructor injection and MUST remain testable without a Spring context.
The core module MUST NOT:
- depend on JavaFX or UI packages;
- depend on HTTP/MCP SDKs, Spring, or concrete external protocol DTOs;
- call `Platform.runLater`;
- perform navigation or workspace selection;
- use presentation severity or visual state as domain semantics;
- obtain dependencies from a static holder or `ApplicationContext` lookup.
The functional core modules are:
- `project`: project identity, catalog, creation, paths, setup, and restoration state;
- `session`: open-project lifecycle, project-scoped automation authority, document handoff, ordered cleanup, execution ownership, and the LSP lifecycle port;
- `assets`: Studio-owned asset projections, metadata, policies, non-visual sessions, validation, and workflow orchestration;
- `shipper`: build/pack coordination, manifest generation, artifacts, and neutral logs/results;
- `runtime`: runtime settings, handshake, process/client lifecycle, canonical capture contracts, and technical logs; human Debug and headless automation retain distinct protocol/lifecycle boundaries;
- `execution`: play/stop and automation operation state, cancellation, shutdown, and orchestration of shipper and runtime.
The functional dependency direction MUST remain:
```text
assets --> project
shipper --> project
runtime --> project
execution --> project, shipper, runtime
session --> project, execution, LSP port
```
Session-owned authority lifetime MUST NOT introduce reverse functional dependencies from `assets`, `shipper`, `runtime` or `execution` to the concrete `session` module. Service entry points MUST receive the shared authority through neutral contracts and composition, not reach into JavaFX or concrete session implementations. Document-handoff participants likewise use neutral contracts; their presentation buffers remain adapter-owned.
Manual Debug and project mutation MUST enforce the same project authority as automation. Disabled UI buttons alone are not authorization. Grant, acquisition, operation completion and authority return MUST remain distinct lifecycle facts.
## JavaFX Adapter Rules
The JavaFX module MUST depend on Studio API contracts rather than core or provider implementations. It owns visual state, UI events, navigation, FX-thread transitions, CSS, fonts, locale bindings, and lifecycle of visual objects.
JavaFX controls and dialogs MUST be constructed by UI factories or composition roots. They MUST NOT become Spring singletons by default.
Presentation-only drafts and projections MAY remain in the JavaFX module. Rules that determine project, asset, build, runtime, or semantic outcomes MUST live behind neutral API contracts and core services.
The JavaFX module MUST NOT directly invoke compiler implementations, `p.packer`, LSP implementations, runtime implementations, or filesystem orchestration.
## Spring Composition
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 random per-Studio-start token, validate Origin and reject unexpected origins, and stop with Studio. Connection authentication MUST NOT grant project/task authority. The token MUST NOT be stored in versioned files, and restart requires refreshed client configuration.
This exception does not authorize a web UI, remote binding, general-purpose web application, accounts, OAuth, or a stdio MCP bridge. HTTP/MCP dependencies MUST NOT enter API/Core or the JavaFX adapter. Spring Data, Spring AI and durable event infrastructure remain outside the accepted architecture.
Spring configuration MAY create core services, infrastructure adapters, and a JavaFX composition factory. It MUST NOT use field injection, context lookup, broad service bags, or a replacement static container.
The desktop entry point MUST retain the JavaFX composition root and close it before closing the Spring context. Closing that root MUST be idempotent and MUST close any active or asynchronously opening project session, execution surface, loading window, project window, and launcher window before provider beans and executors are destroyed.
Spring Modulith verification MUST use `p.studio.core` as its exclusive application root and MUST run as an architecture gate.
## External Integration Rule
An integration MUST use the provider's public API directly when that API is stable, neutral, use-case oriented, and safe to compose and test. A redundant gateway that merely mirrors such an API MUST NOT be created.
A narrow consumer-owned gateway MUST be used when the available integration is concrete, static, infrastructure-oriented, unstable, excessively broad, or leaks lifecycle and implementation details. Its implementation belongs in `prometeu-app` or another explicit infrastructure adapter.
| Studio consumer | Provider | Required boundary |
| --- | --- | --- |
| `assets` | `p.packer` | Stable public Packer API directly; narrow assets-owned gateway only when necessary |
| `shipper` | compiler and `p.packer` | Stable public APIs or a narrow shipper-owned compiler gateway |
| `session` | LSP | Neutral session-owned lifecycle port |
| `runtime` | external runtime/process | Narrow runtime-owned gateway |
| JavaFX UI | Studio | Studio API only |
| MCP adapter | Studio | Studio API only; transport DTO translation belongs to infrastructure |
The headless gateway MUST start `prometeu headless --stdio` from the configured runtime installation and map the runtime-owned JSONL contract to neutral results. It MUST NOT reuse the human DevTools connection, introduce a native Rust/Java binding, search/download another runtime, or redefine firmware/VM semantics. Runtime process supervision and the existing project LSP client belong to application/infrastructure adapters, not UI controls.
`p.packer` remains an autonomous domain and MUST NOT depend on any `p.studio` package. Studio MUST NOT copy or assume ownership of Packer semantics.
## Commands, Events, and Operations
Commands and queries requiring an immediate response MUST use direct service calls. In-process events MAY communicate facts that require no response, and each application event MUST be owned by the functional module that owns the fact.
Selection, navigation, attach/detach, and visual lifecycle events remain UI-local.
Long-running build, pack, runtime, and execution work MUST expose a neutral operation contract with stable identity, observable snapshot, standard-Java asynchronous completion, cancellation, updates, and a typed result.
Core services MUST submit such work through the neutral `OperationExecutor` port. `prometeu-app` owns the executor-backed implementation and its thread lifecycle; JavaFX consumes `OperationHandle` completion and snapshots and performs only the required FX-thread projection.
Automation MUST reuse this operation boundary. Task authority is separate from operation success, guest fault, infrastructure failure or cancellation. Revocation MUST invalidate task authority before stopping managed work, refreshing open documents and releasing manual control. Closing the project or application MUST perform that cleanup; changing the active workspace MUST NOT.
Build and advance admission MUST return a promptly queryable operation identity. Task-scoped, in-memory `clientRequestId` deduplication MUST live behind the shared services, not in a second MCP orchestrator. Runtime `requestId` is wire correlation and MUST NOT be treated as that deduplication mechanism. Late calls/results MUST NOT restore revoked authority.
## Conformance Gates
The architecture is conformant only when all of the following hold together:
- API and core compile without JavaFX, Spring, HTTP/MCP SDKs or concrete transport DTO dependencies;
- UI has no dependency on core or concrete external providers;
- `ApplicationModules.verify()` succeeds for the exclusive `p.studio.core` root;
- the desktop application boots and shuts down with no web exposure other than the authorized loopback MCP endpoint, whose transport is lifecycle-managed by the app;
- MCP and JavaFX consume shared authorization and operations; grant/Debug exclusion and cleanup are enforced in services;
- `Container`, `AppContainer`, compatibility allowlists, and the mixed module are absent;
- unit, integration, architecture, packaging, and desktop smoke tests pass;
- no service locator or context lookup replaces the removed static container.
## Non-Goals
- embedding an agent, chat or provider adapter;
- adding a second orchestration/authorization implementation inside MCP;
- replacing JavaFX with a web UI;
- migrating the Studio to Rust, Electron, Tauri, or a parallel rewrite;
- redesigning compiler, Packer, LSP, or runtime semantics;
- introducing microservices or durable event infrastructure.
+12 -3
View File
@@ -55,6 +55,9 @@ The current Studio core corpus is:
3. [`3. Studio Components Module Specification.md`](3.%20Studio%20Components%20Module%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)
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
@@ -64,7 +67,10 @@ Recommended order:
2. shared UI foundations;
3. components module policy;
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;
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
@@ -72,6 +78,9 @@ The embedded Studio code-editor stack was removed by `DEC-0031`.
Normative reminders:
- the active Studio workspace corpus is `Assets`, `Debug`, and `Shipper`;
- the accepted Studio workspace corpus is `Assets`, `Debug`, `Shipper`, and `DEV`; the DEV implementation follows DEC-0060's phased delivery;
- project-local Studio session state remains normative and is owned by `StudioProjectSession`;
- any future external-editor backend or replacement language-service architecture requires a new accepted decision before new Studio specs are introduced.
- DEC-0060 authorizes an external coding agent using native file tools and the existing project LSP through MCP; it does not reinstate the embedded editor or authorize a replacement language-service architecture;
- the Studio backend is exposed through neutral API contracts shared by JavaFX and the local MCP adapter, without duplicated authority or orchestration;
- Spring Boot remains the desktop composition root with the narrow DEC-0060 local MCP HTTP exception; Spring Modulith still verifies the JavaFX-free `p.studio.core` boundary;
- `p.studio.Container`, `AppContainer`, and the mixed `prometeu-studio` module are not valid final architecture.
+5
View File
@@ -8,6 +8,8 @@ junit-jupiter = "5.12.1"
archunit = "1.4.2"
slf4j = "2.0.7"
lsp4j = "1.0.0"
spring-boot = "3.5.16"
spring-modulith = "1.4.13"
[libraries]
javafx-controls = { group = "org.openjfx", name = "javafx-controls", version.ref = "javafx" }
@@ -24,6 +26,9 @@ archunit-junit5 = { group = "com.tngtech.archunit", name = "archunit-junit5", ve
slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
slf4j-simple = { group = "org.slf4j", name = "slf4j-simple", version.ref = "slf4j" }
lsp4j = { group = "org.eclipse.lsp4j", name = "org.eclipse.lsp4j", version.ref = "lsp4j" }
spring-boot = { group = "org.springframework.boot", name = "spring-boot", version.ref = "spring-boot" }
spring-modulith-core = { group = "org.springframework.modulith", name = "spring-modulith-core", version.ref = "spring-modulith" }
spring-modulith-docs = { group = "org.springframework.modulith", name = "spring-modulith-docs", version.ref = "spring-modulith" }
[plugins]
javafx = { id = "org.openjfx.javafxplugin", version = "0.1.0" }
+56 -2
View File
@@ -7,19 +7,73 @@ dependencies {
implementation(project(":prometeu-infra"))
implementation(project(":prometeu-lsp:prometeu-lsp-api"))
implementation(project(":prometeu-lsp:prometeu-lsp-v1"))
implementation(project(":prometeu-compiler:prometeu-compiler-core"))
implementation(project(":prometeu-compiler:prometeu-build-pipeline"))
implementation(project(":prometeu-compiler:prometeu-frontend-registry"))
implementation(project(":prometeu-compiler:prometeu-deps"))
implementation(project(":prometeu-packer:prometeu-packer-api"))
implementation(project(":prometeu-packer:prometeu-packer-v1"))
implementation(project(":prometeu-studio"))
implementation(project(":prometeu-studio-api"))
implementation(project(":prometeu-studio-core"))
implementation(project(":prometeu-studio-ui-javafx"))
implementation(libs.spring.boot)
implementation(libs.lsp4j)
implementation(libs.javafx.controls)
implementation(libs.javafx.fxml)
}
application {
mainClass = "p.studio.App"
mainClass = "p.studio.app.StudioLauncher"
}
javafx {
version = libs.versions.javafx.get()
modules("javafx.controls", "javafx.fxml")
}
// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests.
tasks.named<Test>("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(""))
}
@@ -1,29 +0,0 @@
package p.studio;
import javafx.application.Application;
import javafx.stage.Stage;
import p.studio.window.StudioWindowCoordinator;
public class App extends Application {
@Override
public void init() throws Exception {
super.init();
Container.install(new AppContainer());
}
@Override
public void start(Stage stage) {
new StudioWindowCoordinator(stage).showLauncher();
}
@Override
public void stop() throws Exception {
Container.shutdown();
super.stop();
}
public static void main(String[] args) {
launch();
}
}
@@ -1,91 +0,0 @@
package p.studio;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.packer.Packer;
import p.studio.compiler.FrontendRegistryService;
import p.studio.lsp.api.LspServerLifecycle;
import p.studio.lsp.events.StudioEventBus;
import p.studio.lsp.events.StudioPackerEventAdapter;
import p.studio.lsp.services.LspServerLifecycleImpl;
import p.studio.utilities.ThemeService;
import p.studio.utilities.i18n.I18nService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public final class AppContainer implements Container {
private final I18nService i18nService;
private final ThemeService themeService;
private final StudioEventBus studioEventBus;
private final ObjectMapper mapper;
private final EmbeddedPacker embeddedPacker;
private final StudioBackgroundTasks backgroundTasks;
private final LspServerLifecycle lspServerLifecycle;
public AppContainer() {
FrontendRegistryService.bootstrapDefaults();
this.i18nService = new I18nService();
this.themeService = new ThemeService();
this.studioEventBus = new StudioEventBus();
this.mapper = new ObjectMapper();
final ExecutorService backgroundExecutor = Executors.newFixedThreadPool(2, new StudioWorkerThreadFactory());
this.backgroundTasks = new StudioBackgroundTasks(backgroundExecutor);
final Packer packer = Packer.bootstrap(this.mapper, new StudioPackerEventAdapter(studioEventBus));
this.embeddedPacker = new EmbeddedPacker(packer.workspaceService(), packer::close);
this.lspServerLifecycle = new LspServerLifecycleImpl();
}
@Override
public I18nService getI18n() {
return i18nService;
}
@Override
public ThemeService getTheme() {
return themeService;
}
@Override
public StudioEventBus getEventBus() {
return studioEventBus;
}
@Override
public ObjectMapper getMapper() {
return mapper;
}
@Override
public EmbeddedPacker getPacker() {
return embeddedPacker;
}
@Override
public StudioBackgroundTasks getBackgroundTasks() {
return backgroundTasks;
}
@Override
public p.studio.lsp.api.LspServerLifecycle getLspServerLifecycle() {
return lspServerLifecycle;
}
@Override
public void shutdownContainer() {
embeddedPacker.shutdown();
backgroundTasks.shutdown();
}
private static final class StudioWorkerThreadFactory implements ThreadFactory {
private final AtomicInteger nextId = new AtomicInteger(1);
@Override
public Thread newThread(Runnable runnable) {
final Thread thread = new Thread(runnable, "studio-worker-" + nextId.getAndIncrement());
thread.setDaemon(true);
return thread;
}
}
}
@@ -0,0 +1,63 @@
package p.studio.app;
import javafx.application.Application;
import javafx.stage.Stage;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import p.studio.ui.javafx.window.StudioWindowCoordinator;
public class App extends Application {
private ConfigurableApplicationContext applicationContext;
private StudioWindowCoordinator studioWindowCoordinator;
@Override
public void init() throws Exception {
super.init();
applicationContext = new SpringApplicationBuilder(StudioApplicationConfiguration.class)
.web(WebApplicationType.NONE)
.headless(false)
.run();
}
@Override
public void start(Stage stage) {
studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).create(stage);
studioWindowCoordinator.showLauncher();
}
@Override
public void stop() throws Exception {
Exception failure = null;
try {
if (studioWindowCoordinator != null) {
studioWindowCoordinator.close();
}
} catch (RuntimeException exception) {
failure = exception;
}
try {
if (applicationContext != null) {
applicationContext.close();
}
} catch (RuntimeException exception) {
failure = append(failure, exception);
}
try {
super.stop();
} catch (Exception exception) {
failure = append(failure, exception);
}
if (failure != null) {
throw failure;
}
}
private static Exception append(Exception prior, Exception failure) {
if (prior == null) {
return failure;
}
prior.addSuppressed(failure);
return prior;
}
}
@@ -0,0 +1,370 @@
package p.studio.app;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import p.packer.PackerWorkspaceService;
import p.studio.api.project.KnownProjects;
import p.studio.api.assets.AssetCatalog;
import p.studio.api.assets.AssetCommands;
import p.studio.api.assets.AssetPacking;
import p.studio.api.assets.AssetDetails;
import p.studio.api.assets.AssetCreationCatalog;
import p.studio.api.assets.AssetWorkspaceStorage;
import p.studio.api.assets.AssetCapacityPolicy;
import p.studio.api.assets.schema.AssetColorSchemaFactory;
import p.studio.api.assets.bank.AssetBankCompositionSessionFactory;
import p.studio.api.assets.metadata.AssetMetadataService;
import p.studio.core.assets.PackerAssetCatalog;
import p.studio.core.assets.PackerAssetCommands;
import p.studio.core.assets.PackerAssetPacking;
import p.studio.core.assets.PackerAssetDetails;
import p.studio.core.assets.PackerAssetCreationCatalog;
import p.studio.core.assets.FileSystemAssetWorkspaceStorage;
import p.studio.core.assets.DefaultAssetCapacityPolicy;
import p.studio.core.assets.schema.DefaultAssetColorSchemaFactory;
import p.studio.core.assets.bank.DefaultAssetBankCompositionSessionFactory;
import p.studio.core.assets.metadata.AssetStudioMetadataService;
import p.studio.api.assets.scene.SceneBankWorkflow;
import p.studio.api.assets.tiled.TiledAssetService;
import p.studio.core.assets.scene.SceneBankWorkflowService;
import p.studio.core.assets.tiled.TiledAssetGenerationService;
import p.studio.api.project.ProjectCatalog;
import p.studio.api.project.ProjectLanguageCatalog;
import p.studio.app.compiler.CompilerProjectLanguageCatalog;
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
import p.studio.api.shipper.Shipper;
import p.studio.core.shipper.CompilerBuildGateway;
import p.studio.core.shipper.StudioShipperService;
import p.studio.core.project.KnownProjectsService;
import p.studio.core.project.ProjectCatalogService;
import p.studio.core.project.ProjectLocalStudioSetupStore;
import p.studio.core.project.ProjectLocalStudioStateStore;
import p.studio.api.project.ProjectWorkspaceInitializer;
import p.studio.core.project.PackerProjectWorkspaceInitializer;
import p.studio.api.session.ProjectSessionFactory;
import p.studio.app.lsp.LspLifecycleAdapter;
import p.studio.core.session.DefaultProjectSessionFactory;
import p.studio.core.session.LspLifecyclePort;
import p.studio.lsp.api.LspServerLifecycle;
import p.studio.lsp.services.LspServerLifecycleImpl;
import p.studio.ui.javafx.events.StudioEventBus;
import p.studio.ui.javafx.utilities.ThemeService;
import p.studio.ui.javafx.utilities.i18n.I18nService;
import p.packer.Packer;
import p.studio.compiler.FrontendRegistryService;
import p.studio.api.execution.ExecutionControllerFactory;
import p.studio.app.runtime.ExternalRuntimeGateway;
import p.studio.core.execution.DefaultExecutionControllerFactory;
import p.studio.core.runtime.RuntimeGateway;
import p.studio.api.preferences.WindowStateStore;
import p.studio.core.project.preferences.JsonWindowStateStore;
import p.studio.api.preferences.ProjectActivityHistoryStore;
import p.studio.core.project.preferences.JsonProjectActivityHistoryStore;
import p.studio.api.operation.OperationExecutor;
import p.studio.app.operation.ExecutorOperationExecutor;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Configuration(proxyBeanMethods = false)
public class StudioApplicationConfiguration {
@Bean
ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Bean
I18nService i18nService() {
return new I18nService();
}
@Bean
ThemeService themeService() {
return new ThemeService();
}
@Bean
StudioEventBus studioEventBus() {
return new StudioEventBus();
}
@Bean(destroyMethod = "close")
Packer packer(ObjectMapper mapper, StudioEventBus events) {
return Packer.bootstrap(mapper, new StudioPackerEventAdapter(events));
}
@Bean
PackerWorkspaceService packerWorkspaceService(Packer packer) {
return packer.workspaceService();
}
@Bean
AssetCatalog assetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) {
return new PackerAssetCatalog(packer, access);
}
@Bean
AssetCommands assetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) {
return new PackerAssetCommands(packer, access);
}
@Bean
AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new PackerAssetPacking(packer, operations, access);
}
@Bean
AssetDetails assetDetails(PackerWorkspaceService packer) {
return new PackerAssetDetails(packer);
}
@Bean
AssetCreationCatalog assetCreationCatalog() {
return new PackerAssetCreationCatalog();
}
@Bean
AssetWorkspaceStorage assetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) {
return new FileSystemAssetWorkspaceStorage(access);
}
@Bean
AssetCapacityPolicy assetCapacityPolicy() {
return new DefaultAssetCapacityPolicy();
}
@Bean
AssetColorSchemaFactory assetColorSchemaFactory() {
return new DefaultAssetColorSchemaFactory();
}
@Bean
AssetBankCompositionSessionFactory assetBankCompositionSessionFactory(AssetCapacityPolicy capacityPolicy) {
return new DefaultAssetBankCompositionSessionFactory(capacityPolicy);
}
@Bean
AssetMetadataService assetMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
return new AssetStudioMetadataService(mapper, access);
}
@Bean
SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
return new SceneBankWorkflowService(assetCatalog, mapper, access);
}
@Bean
TiledAssetService tiledAssetService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) {
return new TiledAssetGenerationService(metadataService, access);
}
@Bean
WindowStateStore windowStateStore(ObjectMapper mapper) {
return new JsonWindowStateStore(resolveWindowStateStorage(), mapper);
}
@Bean
ProjectActivityHistoryStore projectActivityHistoryStore(ObjectMapper mapper) {
return new JsonProjectActivityHistoryStore(mapper);
}
@Bean
CompilerBuildGateway compilerBuildGateway() {
return new CompilerBuildGatewayAdapter();
}
@Bean
StudioShipperService shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper,
OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new StudioShipperService(compiler, packer, mapper, operations, access);
}
@Bean(destroyMethod = "shutdown")
ExecutorService studioExecutor() {
return Executors.newFixedThreadPool(4, Thread.ofPlatform().daemon().name("studio-worker-", 1).factory());
}
@Bean
OperationExecutor operationExecutor(ExecutorService studioExecutor) {
return new ExecutorOperationExecutor(studioExecutor);
}
@Bean
RuntimeGateway runtimeGateway(ObjectMapper mapper, ExecutorService studioExecutor) {
return new ExternalRuntimeGateway(mapper, studioExecutor);
}
@Bean
ExecutionControllerFactory executionControllerFactory(Shipper shipper, RuntimeGateway runtime,
OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new DefaultExecutionControllerFactory(shipper, runtime, operations, access);
}
@Bean
ProjectLocalStudioSetupStore projectLocalStudioSetupStore(ObjectMapper mapper) {
return new ProjectLocalStudioSetupStore(mapper);
}
@Bean
ProjectLocalStudioStateStore projectLocalStudioStateStore(ObjectMapper mapper) {
return new ProjectLocalStudioStateStore(mapper);
}
@Bean
LspServerLifecycle lspServerLifecycle() {
return new LspServerLifecycleImpl();
}
@Bean
LspLifecyclePort lspLifecyclePort(LspServerLifecycle lifecycle) {
return new LspLifecycleAdapter(lifecycle);
}
@Bean
p.studio.core.project.ProjectAccessRegistry projectAccessRegistry() {
return new p.studio.core.project.ProjectAccessRegistry();
}
@Bean(destroyMethod = "close")
DefaultProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore,
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) {
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations);
}
@Bean
ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) {
return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore);
}
@Bean
KnownProjects knownProjects(ProjectCatalog projectCatalog) {
return new KnownProjectsService(resolveKnownProjectsStorage(), projectCatalog);
}
@Bean
ProjectWorkspaceInitializer projectWorkspaceInitializer(PackerWorkspaceService packer) {
return new PackerProjectWorkspaceInitializer(packer);
}
@Bean
ProjectLanguageCatalog projectLanguageCatalog() {
FrontendRegistryService.bootstrapDefaults();
return new CompilerProjectLanguageCatalog();
}
@Bean
StudioUiFactory studioUiFactory(
ProjectCatalog projectCatalog,
KnownProjects knownProjects,
ProjectLanguageCatalog languageCatalog,
ProjectSessionFactory projectSessionFactory,
ExecutionControllerFactory executionControllerFactory,
ProjectWorkspaceInitializer projectWorkspaceInitializer,
ExecutorService studioExecutor,
I18nService i18n,
ThemeService theme,
StudioEventBus eventBus,
Shipper shipper,
AssetCatalog assetCatalog,
AssetCommands assetCommands,
AssetPacking assetPacking,
AssetDetails assetDetails,
AssetCreationCatalog assetCreationCatalog,
AssetMetadataService assetMetadataService,
AssetWorkspaceStorage assetWorkspaceStorage,
AssetCapacityPolicy assetCapacityPolicy,
AssetBankCompositionSessionFactory bankCompositionSessionFactory,
AssetColorSchemaFactory assetColorSchemaFactory,
TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) {
return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, 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.AgentConnectionGuide connectionGuide(p.studio.app.mcp.LocalMcpServer server,
p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper) {
return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper);
}
private static Path resolveDefaultProjectsRoot() {
Path cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
while (cursor != null) {
if (cursor.resolve("settings.gradle.kts").toFile().exists()
&& cursor.resolve("test-projects").toFile().exists()) {
return cursor.resolve("test-projects");
}
cursor = cursor.getParent();
}
return Path.of("test-projects").toAbsolutePath().normalize();
}
private static Path resolveKnownProjectsStorage() {
return Path.of(System.getProperty("user.home"), ".prometeu-studio", "known-projects.txt")
.toAbsolutePath().normalize();
}
private static Path resolveWindowStateStorage() {
return Path.of(System.getProperty("user.home"), ".prometeu-studio", "window-state.json")
.toAbsolutePath().normalize();
}
}
@@ -0,0 +1,12 @@
package p.studio.app;
import javafx.application.Application;
public final class StudioLauncher {
private StudioLauncher() {
}
public static void main(String[] args) {
Application.launch(App.class, args);
}
}
@@ -1,14 +1,17 @@
package p.studio.lsp.events;
package p.studio.app;
import p.packer.events.PackerEvent;
import p.packer.events.PackerEventSink;
import p.studio.ui.javafx.events.StudioEventBus;
import p.studio.ui.javafx.events.StudioPackerOperationEvent;
import p.studio.ui.javafx.events.StudioPackerOperationKind;
import java.util.Objects;
public final class StudioPackerEventAdapter implements PackerEventSink {
final class StudioPackerEventAdapter implements PackerEventSink {
private final StudioEventBus eventBus;
public StudioPackerEventAdapter(StudioEventBus eventBus) {
StudioPackerEventAdapter(StudioEventBus eventBus) {
this.eventBus = Objects.requireNonNull(eventBus, "eventBus");
}
@@ -17,7 +20,7 @@ public final class StudioPackerEventAdapter implements PackerEventSink {
final PackerEvent packerEvent = Objects.requireNonNull(event, "event");
eventBus.publish(new StudioPackerOperationEvent(
packerEvent.operationId(),
packerEvent.kind(),
StudioPackerOperationKind.valueOf(packerEvent.kind().name()),
packerEvent.summary(),
packerEvent.progress() == null ? null : packerEvent.progress().value(),
packerEvent.progress() == null || packerEvent.progress().indeterminate()));
@@ -0,0 +1,123 @@
package p.studio.app;
import javafx.stage.Stage;
import p.studio.api.assets.AssetCatalog;
import p.studio.api.assets.AssetCommands;
import p.studio.api.assets.AssetPacking;
import p.studio.api.assets.AssetDetails;
import p.studio.api.assets.AssetCreationCatalog;
import p.studio.api.assets.AssetWorkspaceStorage;
import p.studio.api.assets.AssetCapacityPolicy;
import p.studio.api.assets.schema.AssetColorSchemaFactory;
import p.studio.api.assets.bank.AssetBankCompositionSessionFactory;
import p.studio.api.assets.metadata.AssetMetadataService;
import p.studio.api.assets.scene.SceneBankWorkflow;
import p.studio.api.assets.tiled.TiledAssetService;
import p.studio.api.project.KnownProjects;
import p.studio.api.project.ProjectCatalog;
import p.studio.api.project.ProjectLanguageCatalog;
import p.studio.api.shipper.Shipper;
import p.studio.api.session.ProjectSessionFactory;
import p.studio.api.execution.ExecutionControllerFactory;
import p.studio.api.project.ProjectWorkspaceInitializer;
import p.studio.api.preferences.WindowStateStore;
import p.studio.api.preferences.ProjectActivityHistoryStore;
import p.studio.ui.javafx.window.StudioWindowCoordinator;
import java.util.Objects;
import java.util.concurrent.Executor;
import p.studio.ui.javafx.utilities.ThemeService;
import p.studio.ui.javafx.utilities.i18n.I18nService;
import p.studio.ui.javafx.events.StudioEventBus;
public final class StudioUiFactory {
private final ProjectCatalog projectCatalog;
private final KnownProjects knownProjects;
private final ProjectLanguageCatalog languageCatalog;
private final ProjectSessionFactory projectSessionFactory;
private final ExecutionControllerFactory executionControllerFactory;
private final ProjectWorkspaceInitializer projectWorkspaceInitializer;
private final Executor executor;
private final I18nService i18n;
private final ThemeService theme;
private final StudioEventBus eventBus;
private final Shipper shipper;
private final AssetCatalog assetCatalog;
private final AssetCommands assetCommands;
private final AssetPacking assetPacking;
private final AssetDetails assetDetails;
private final AssetCreationCatalog assetCreationCatalog;
private final AssetMetadataService assetMetadataService;
private final AssetWorkspaceStorage assetWorkspaceStorage;
private final AssetCapacityPolicy assetCapacityPolicy;
private final AssetBankCompositionSessionFactory bankCompositionSessionFactory;
private final AssetColorSchemaFactory assetColorSchemaFactory;
private final TiledAssetService tiledAssetService;
private final SceneBankWorkflow sceneBankWorkflow;
private final WindowStateStore windowStateStore;
private final ProjectActivityHistoryStore activityHistoryStore;
private final p.studio.api.automation.AgentConnectionGuide connectionGuide;
public StudioUiFactory(
ProjectCatalog projectCatalog,
KnownProjects knownProjects,
ProjectLanguageCatalog languageCatalog,
ProjectSessionFactory projectSessionFactory,
ExecutionControllerFactory executionControllerFactory,
ProjectWorkspaceInitializer projectWorkspaceInitializer,
Executor executor,
I18nService i18n,
ThemeService theme,
StudioEventBus eventBus,
Shipper shipper,
AssetCatalog assetCatalog,
AssetCommands assetCommands,
AssetPacking assetPacking,
AssetDetails assetDetails,
AssetCreationCatalog assetCreationCatalog,
AssetMetadataService assetMetadataService,
AssetWorkspaceStorage assetWorkspaceStorage,
AssetCapacityPolicy assetCapacityPolicy,
AssetBankCompositionSessionFactory bankCompositionSessionFactory,
AssetColorSchemaFactory assetColorSchemaFactory,
TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) {
this.connectionGuide = Objects.requireNonNull(connectionGuide);
this.projectCatalog = Objects.requireNonNull(projectCatalog, "projectCatalog");
this.knownProjects = Objects.requireNonNull(knownProjects, "knownProjects");
this.languageCatalog = Objects.requireNonNull(languageCatalog, "languageCatalog");
this.projectSessionFactory = Objects.requireNonNull(projectSessionFactory, "projectSessionFactory");
this.executionControllerFactory = Objects.requireNonNull(executionControllerFactory, "executionControllerFactory");
this.projectWorkspaceInitializer = Objects.requireNonNull(projectWorkspaceInitializer, "projectWorkspaceInitializer");
this.executor = Objects.requireNonNull(executor, "executor");
this.i18n = Objects.requireNonNull(i18n, "i18n");
this.theme = Objects.requireNonNull(theme, "theme");
this.eventBus = Objects.requireNonNull(eventBus, "eventBus");
this.shipper = Objects.requireNonNull(shipper, "shipper");
this.assetCatalog = Objects.requireNonNull(assetCatalog, "assetCatalog");
this.assetCommands = Objects.requireNonNull(assetCommands, "assetCommands");
this.assetPacking = Objects.requireNonNull(assetPacking, "assetPacking");
this.assetDetails = Objects.requireNonNull(assetDetails, "assetDetails");
this.assetCreationCatalog = Objects.requireNonNull(assetCreationCatalog, "assetCreationCatalog");
this.assetMetadataService = Objects.requireNonNull(assetMetadataService, "assetMetadataService");
this.assetWorkspaceStorage = Objects.requireNonNull(assetWorkspaceStorage, "assetWorkspaceStorage");
this.assetCapacityPolicy = Objects.requireNonNull(assetCapacityPolicy, "assetCapacityPolicy");
this.bankCompositionSessionFactory = Objects.requireNonNull(bankCompositionSessionFactory, "bankCompositionSessionFactory");
this.assetColorSchemaFactory = Objects.requireNonNull(assetColorSchemaFactory, "assetColorSchemaFactory");
this.tiledAssetService = Objects.requireNonNull(tiledAssetService, "tiledAssetService");
this.sceneBankWorkflow = Objects.requireNonNull(sceneBankWorkflow, "sceneBankWorkflow");
this.windowStateStore = Objects.requireNonNull(windowStateStore, "windowStateStore");
this.activityHistoryStore = Objects.requireNonNull(activityHistoryStore, "activityHistoryStore");
}
public StudioWindowCoordinator create(Stage stage) {
return new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, executor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, connectionGuide);
}
}
@@ -0,0 +1,25 @@
package p.studio.app.compiler;
import p.studio.api.project.ProjectReference;
import p.studio.compiler.messages.BuilderPipelineConfig;
import p.studio.compiler.models.BuilderPipelineContext;
import p.studio.compiler.workspaces.BuilderPipelineService;
import p.studio.core.shipper.CompilerBuildGateway;
import p.studio.utilities.logs.LogAggregator;
import java.util.LinkedHashSet;
import java.util.function.Consumer;
public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway {
@Override
public CompilerBuildOutput compile(ProjectReference project, Consumer<String> logSink) {
final var config = new BuilderPipelineConfig(false, project.rootPath().toString());
final var result = BuilderPipelineService.INSTANCE.build(
BuilderPipelineContext.fromConfig(config),
LogAggregator.with(logSink));
final var capabilities = new LinkedHashSet<>(
result.compileResult().analysisSnapshot().irBackend()
.getReservedMetadata().requiredCapabilities().asList());
return new CompilerBuildOutput(result.bytecodeArtifactPath(), capabilities.stream().toList());
}
}
@@ -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,36 @@
package p.studio.app.compiler;
import p.studio.api.project.ProjectLanguageCatalog;
import p.studio.api.project.ProjectLanguageTemplate;
import p.studio.compiler.FrontendRegistryService;
import p.studio.compiler.models.FrontendSpec;
import java.util.Comparator;
import java.util.List;
public final class CompilerProjectLanguageCatalog implements ProjectLanguageCatalog {
@Override
public List<ProjectLanguageTemplate> listLanguageTemplates() {
return FrontendRegistryService.listProviders().stream()
.map(provider -> toTemplate(provider.specification()))
.sorted(Comparator.comparing(ProjectLanguageTemplate::languageId, String.CASE_INSENSITIVE_ORDER))
.toList();
}
private ProjectLanguageTemplate toTemplate(FrontendSpec spec) {
final List<String> roots = spec.getSourceRoots().stream().sorted(String.CASE_INSENSITIVE_ORDER).toList();
final List<ProjectLanguageTemplate.StdlibOption> options = spec.getStdlibVersions().stream()
.map(value -> new ProjectLanguageTemplate.StdlibOption(
value.version(), ProjectLanguageTemplate.Stability.valueOf(value.type().name())))
.sorted(Comparator.comparingInt(ProjectLanguageTemplate.StdlibOption::version))
.toList();
final ProjectLanguageTemplate.StdlibOption defaultOption = options.stream()
.filter(value -> value.stability() == ProjectLanguageTemplate.Stability.DEFAULT)
.findFirst().orElseGet(() -> options.isEmpty()
? new ProjectLanguageTemplate.StdlibOption(1, ProjectLanguageTemplate.Stability.DEFAULT)
: options.getFirst());
return new ProjectLanguageTemplate(
spec.getLanguageId(), options, defaultOption, roots,
roots.isEmpty() ? "src" : roots.getFirst());
}
}
@@ -0,0 +1,245 @@
package p.studio.app.lsp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.lsp4j.*;
import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.launch.LSPLauncher;
import org.eclipse.lsp4j.services.*;
import p.studio.api.automation.*;
import p.studio.api.project.ProjectCatalog;
import p.studio.core.language.LanguageQueryPort;
import p.studio.lsp.api.LspServerLifecycle;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
/** A real client of the already-running project LSP. Each query owns and closes its connection. */
public final class AutomationLspQueries implements LanguageQueryPort {
private final LspServerLifecycle lifecycle;
private final ProjectCatalog projects;
private final ProjectKnowledge knowledge;
private final ObjectMapper mapper;
private final com.google.gson.Gson gson = new MessageJsonHandler(Map.of()).getGson();
private final Map<TaskIdentity, Map<String, CallHierarchyItem>> items = new ConcurrentHashMap<>();
private static final Set<String> OPERATIONS = Set.of("diagnostics", "completion", "hover", "signatureHelp", "definition",
"references", "documentSymbols", "workspaceSymbols", "prepareRename", "rename", "codeActions", "formatting",
"documentLinks", "foldingRanges", "selectionRanges", "prepareCallHierarchy", "incomingCalls", "outgoingCalls", "semanticTokens");
private static final Set<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;
}
@Override public void endTask(TaskIdentity task) { items.remove(task); }
@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");
}
Path document = uri == null ? null : sourcePath(context, uri);
if (document != null && EDITS.contains(operation)) requireEditable(context, document.toUri().toString());
String source = null;
if (document != null) {
try (var input = Files.newInputStream(document)) {
var bytes = input.readNBytes(4 * 1024 * 1024 + 1);
if (bytes.length > 4 * 1024 * 1024) throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Source document exceeds 4 MiB");
source = java.nio.charset.StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString();
}
uri = document.toUri().toString();
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
var workers = Executors.newCachedThreadPool(r -> { var thread = new Thread(r, "studio-automation-lsp"); thread.setDaemon(true); return thread; });
try (var socket = new Socket()) {
if (!InetAddress.getByName(endpoint.host()).isLoopbackAddress()) throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Project LSP endpoint is not local");
socket.connect(new InetSocketAddress(endpoint.host(), endpoint.port()), 2000);
var diagnostics = new CompletableFuture<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 = LSPLauncher.createClientLauncher(client, socket.getInputStream(), socket.getOutputStream(), workers, consumer -> consumer);
var listening = launcher.startListening();
try {
var server = launcher.getRemoteProxy();
var initialize = new InitializeParams();
initialize.setRootUri(binding.projectRoot().toUri().toString());
initialize.setCapabilities(new ClientCapabilities());
var capabilities = await(server.initialize(initialize), deadline).getCapabilities();
server.initialized(new InitializedParams());
requireCapability(operation, capabilities);
List<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);
}
var text = server.getTextDocumentService();
var id = uri == null ? null : new TextDocumentIdentifier(uri);
Object result = switch (operation) {
case "diagnostics" -> currentDiagnostics;
case "hover" -> await(text.hover(new HoverParams(id, position(params.path("position"), source))), deadline);
case "completion" -> await(text.completion(new CompletionParams(id, position(params.path("position"), source))), deadline);
case "signatureHelp" -> await(text.signatureHelp(new SignatureHelpParams(id, position(params.path("position"), source))), deadline);
case "definition" -> await(text.definition(new DefinitionParams(id, position(params.path("position"), source))), deadline);
case "references" -> await(text.references(new ReferenceParams(id, position(params.path("position"), source), new ReferenceContext(params.path("includeDeclaration").asBoolean(false)))), deadline);
case "documentSymbols" -> await(text.documentSymbol(new DocumentSymbolParams(id)), deadline);
case "workspaceSymbols" -> await(server.getWorkspaceService().symbol(new WorkspaceSymbolParams(params.path("query").asText(""))), deadline);
case "prepareRename" -> await(text.prepareRename(new PrepareRenameParams(id, position(params.path("position"), source))), deadline);
case "rename" -> {
String name = params.path("newName").asText("");
if (name.isBlank()) throw new IllegalArgumentException("newName is required");
yield await(text.rename(new RenameParams(id, position(params.path("position"), source), name)), deadline);
}
case "formatting" -> await(text.formatting(new DocumentFormattingParams(id, new FormattingOptions(4, true))), deadline);
case "codeActions" -> await(text.codeAction(new CodeActionParams(id,
range(params.path("range"), source),
new CodeActionContext(currentDiagnostics))), deadline);
case "documentLinks" -> await(text.documentLink(new DocumentLinkParams(id)), deadline);
case "foldingRanges" -> await(text.foldingRange(new FoldingRangeRequestParams(id)), deadline);
case "selectionRanges" -> {
if (!params.path("positions").isArray() || params.path("positions").isEmpty()) throw new IllegalArgumentException("positions are required");
var positions = new ArrayList<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);
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);
return Collections.unmodifiableMap(output);
} finally { listening.cancel(true); }
} finally { workers.shutdownNow(); }
}
private void addItemIds(TaskIdentity task, com.fasterxml.jackson.databind.JsonNode node) {
if (node.isObject() && node.has("uri") && node.has("selectionRange") && node.has("name") && node.has("kind")) {
var stored = items.computeIfAbsent(task, ignored -> new ConcurrentHashMap<>());
if (stored.size() >= 1024) throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Too many hierarchy items for this task");
String key = UUID.randomUUID().toString();
stored.put(key, gson.fromJson(node.toString(), CallHierarchyItem.class));
((com.fasterxml.jackson.databind.node.ObjectNode) node).put("itemId", key);
} else if (node.isContainerNode()) node.forEach(child -> addItemIds(task, child));
}
private static void requireCapability(String operation, ServerCapabilities caps) {
Object capability = switch (operation) {
case "diagnostics" -> caps.getTextDocumentSync();
case "hover" -> caps.getHoverProvider(); case "completion" -> caps.getCompletionProvider();
case "signatureHelp" -> caps.getSignatureHelpProvider(); case "definition" -> caps.getDefinitionProvider();
case "references" -> caps.getReferencesProvider(); case "documentSymbols" -> caps.getDocumentSymbolProvider();
case "workspaceSymbols" -> caps.getWorkspaceSymbolProvider(); case "rename", "prepareRename" -> caps.getRenameProvider();
case "codeActions" -> caps.getCodeActionProvider(); case "formatting" -> caps.getDocumentFormattingProvider();
case "documentLinks" -> caps.getDocumentLinkProvider(); case "foldingRanges" -> caps.getFoldingRangeProvider();
case "selectionRanges" -> caps.getSelectionRangeProvider(); case "prepareCallHierarchy", "incomingCalls", "outgoingCalls" -> caps.getCallHierarchyProvider();
case "semanticTokens" -> caps.getSemanticTokensProvider(); default -> null;
};
if (capability instanceof Either<?, ?> either) capability = either.isLeft() ? either.getLeft() : either.getRight();
if (operation.equals("prepareRename") && (!(capability instanceof RenameOptions options) || !Boolean.TRUE.equals(options.getPrepareProvider())))
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise prepareRename");
if (capability == null || Boolean.FALSE.equals(capability)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise " + operation);
}
private static Position position(com.fasterxml.jackson.databind.JsonNode node, String text) {
if (!node.path("line").isIntegralNumber() || !node.path("character").isIntegralNumber()
|| !node.path("line").canConvertToInt() || !node.path("character").canConvertToInt()) throw new IllegalArgumentException("UTF-16 position is required");
int line = node.path("line").intValue(), character = node.path("character").intValue();
String[] lines = text.split("\\r\\n|\\n|\\r", -1);
if (line < 0 || line >= lines.length || character < 0 || character > lines[line].length()
|| character > 0 && character < lines[line].length() && Character.isHighSurrogate(lines[line].charAt(character - 1)) && Character.isLowSurrogate(lines[line].charAt(character)))
throw new IllegalArgumentException("Position is outside the saved document or splits a UTF-16 pair");
return new Position(line, character);
}
private static Range range(com.fasterxml.jackson.databind.JsonNode node, String text) {
var start = position(node.path("start"), text); var end = position(node.path("end"), text);
if (start.getLine() > end.getLine() || start.getLine() == end.getLine() && start.getCharacter() > end.getCharacter())
throw new IllegalArgumentException("Range end precedes its start");
return new Range(start, end);
}
private static Path sourcePath(ProjectKnowledge.Context context, String uri) throws Exception {
final Path path;
try { path = Path.of(URI.create(uri)).toRealPath(); }
catch (RuntimeException | java.io.IOException invalid) { throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Source URI is not an accessible local project/dependency file"); }
boolean scope = path.startsWith(context.projectRoot()) || context.readOnlyRoots().stream().anyMatch(path::startsWith)
|| context.libraries().stream().flatMap(lib -> lib.roots().stream()).anyMatch(path::startsWith);
boolean source = context.languages().stream().flatMap(lang -> lang.extensions().stream()).anyMatch(extension -> path.getFileName().toString().endsWith("." + extension));
if (!scope || !source || !Files.isRegularFile(path)) throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "URI is outside the known source scope");
return path;
}
private static void requireEditable(ProjectKnowledge.Context context, String uri) throws Exception {
Path path = sourcePath(context, uri);
if (!path.startsWith(context.projectRoot()) || context.readOnlyRoots().stream().anyMatch(path::startsWith))
throw failure(AutomationFailure.Code.READ_ONLY_SCOPE, "LSP edit proposal targets a read-only SDK/dependency");
}
private static void validateEdits(ProjectKnowledge.Context context, com.fasterxml.jackson.databind.JsonNode node) throws Exception {
if (node.isObject()) {
if (node.has("changes")) {
var fields = node.path("changes").fieldNames();
while (fields.hasNext()) requireEditable(context, fields.next());
}
if (node.has("textDocument") && node.has("edits")) requireEditable(context, node.path("textDocument").path("uri").asText());
if (node.has("kind") && Set.of("create", "rename", "delete").contains(node.path("kind").asText()))
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP file operations are not exposed");
}
if (node.isContainerNode()) for (var child : node) validateEdits(context, child);
}
private static <T> 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 == -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); }
}
@@ -0,0 +1,43 @@
package p.studio.app.lsp;
import p.studio.api.project.ProjectReference;
import p.studio.core.session.LspLifecyclePort;
import p.studio.lsp.api.LspServerLifecycle;
import p.studio.lsp.messages.LspProjectContext;
import p.studio.lsp.messages.LspServerConfiguration;
import java.util.Objects;
public final class LspLifecycleAdapter implements LspLifecyclePort {
private final LspServerLifecycle lifecycle;
private final java.util.Map<java.nio.file.Path, LspProjectContext> bindings = new java.util.concurrent.ConcurrentHashMap<>();
public LspLifecycleAdapter(LspServerLifecycle lifecycle) {
this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle");
}
@Override
public void boot(ProjectReference project) {
var binding = context(project);
lifecycle.bootServer(LspServerConfiguration.builder().endpoint(
new p.studio.lsp.messages.LspServerEndpoint("127.0.0.1", 0)).build(), binding);
bindings.put(project.rootPath().toAbsolutePath().normalize(), binding);
}
@Override
public void shutdown(ProjectReference project) {
var binding = bindings.remove(project.rootPath().toAbsolutePath().normalize());
if (binding != null) lifecycle.shutdownServer(binding);
}
static LspProjectContext context(ProjectReference project) {
final var safeProject = Objects.requireNonNull(project, "project");
final java.nio.file.Path root;
try { root = safeProject.rootPath().toRealPath(); }
catch (java.io.IOException failure) { throw new IllegalStateException("Project root unavailable", failure); }
return new LspProjectContext(
root.toString(),
safeProject.languageId(),
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,214 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.charset.*;
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/** Local MCP transport only. A connection session never represents a project grant or task. */
public final class LocalMcpServer implements AutoCloseable {
public static final String PROTOCOL_VERSION = "2025-06-18";
private static final int MAX_BODY_BYTES = 1024 * 1024;
private static final int MAX_CONNECTION_SESSIONS = 128;
private final ObjectMapper mapper;
private final McpToolRegistry tools;
private final Map<String, AtomicBoolean> sessions = new ConcurrentHashMap<>();
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 synchronized void start() throws IOException {
if (server != null) return;
// No configurable bind address: remote and wildcard exposure cannot be enabled accidentally.
var next = HttpServer.create(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 32);
var workers = new ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(32),
Thread.ofPlatform().daemon().name("studio-mcp-", 1).factory(), new ThreadPoolExecutor.AbortPolicy());
var timers = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-deadlines").factory());
try {
connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"), secret());
deadlines = timers;
next.createContext("/mcp", this::handle);
next.setExecutor(workers);
next.start();
executor = workers; server = next;
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
} catch (RuntimeException failure) {
next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null;
throw failure;
}
}
public Connection connection() {
var current = connection;
if (current == null) throw new IllegalStateException("MCP is not running");
return current;
}
public synchronized boolean isRunning() { return server != null; }
@Override public synchronized void close() {
if (server == null) return;
connection = null; server.stop(0); server = null;
sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow();
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
}
/** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */
public static final class Connection {
private final URI endpoint;
private final String token;
private Connection(URI endpoint, String token) { this.endpoint = endpoint; this.token = token; }
public URI endpoint() { return endpoint; }
public String authorizationHeader() { return "Bearer " + token; }
@Override public String toString() { return "LocalMcpConnection[endpoint=" + endpoint + ", credentials=REDACTED]"; }
}
private void handle(HttpExchange exchange) throws IOException {
// Bounds stalled body reads and transport responses, not guest simulated time or task lifetime.
var timeout = deadlines.schedule(exchange::close, 15, TimeUnit.SECONDS);
try (exchange) {
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
var current = connection;
if (current == null) { empty(exchange, 503); return; }
if (!"/mcp".equals(exchange.getRequestURI().getRawPath()) || exchange.getRequestURI().getRawQuery() != null) { empty(exchange, 404); return; }
var headers = exchange.getRequestHeaders();
String origin = single(headers, "Origin");
String authority = current.endpoint().getRawAuthority();
if (!exchange.getRemoteAddress().getAddress().isLoopbackAddress()
|| !authority.equals(single(headers, "Host"))
|| origin != null && !("http://" + authority).equals(origin)) { empty(exchange, 403); return; }
String authorization = single(headers, "Authorization");
if (authorization == null || !MessageDigest.isEqual(current.authorizationHeader().getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) {
empty(exchange, 401); return;
}
String version = single(headers, "MCP-Protocol-Version");
if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; }
String sessionId = single(headers, "Mcp-Session-Id");
AtomicBoolean initialized = sessionId == null ? null : sessions.get(sessionId);
if (sessionId != null && initialized == null) { empty(exchange, 404); return; }
String method = exchange.getRequestMethod();
if (method.equals("GET")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; }
if (method.equals("DELETE")) {
if (sessionId == null) { empty(exchange, 400); return; }
sessions.remove(sessionId); empty(exchange, 200); return; // No project/task release.
}
if (!method.equals("POST")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; }
if (!accepts(headers, "application/json") || !accepts(headers, "text/event-stream")) { empty(exchange, 406); return; }
String contentType = single(headers, "Content-Type");
if (contentType == null || !contentType.split(";", 2)[0].trim().equalsIgnoreCase("application/json")) { empty(exchange, 415); return; }
byte[] body = exchange.getRequestBody().readNBytes(MAX_BODY_BYTES + 1);
if (body.length > MAX_BODY_BYTES) { empty(exchange, 413); return; }
JsonNode message;
try {
String json = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body)).toString();
message = mapper.readTree(json);
} catch (IOException invalid) { send(exchange, 400, error(NullNode.instance, -32700, "Invalid JSON")); return; }
if (message == null || !message.isObject() || !message.path("jsonrpc").isTextual() || !message.path("jsonrpc").asText().equals("2.0")
|| message.has("id") && !(message.get("id").isTextual() || message.get("id").isNumber())) {
send(exchange, 400, error(NullNode.instance, -32600, "Invalid request")); return;
}
JsonNode id = message.path("id");
String rpc = message.path("method").asText();
if (!message.path("method").isTextual() || rpc.isBlank() || message.has("result") || message.has("error")) {
// This server issues no requests, but acknowledge well-formed client responses.
if (initialized != null && message.has("id") && !message.has("method") && message.has("result") != message.has("error")) empty(exchange, 202);
else send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32600, "Invalid request"));
return;
}
JsonNode params = message.has("params") ? message.get("params") : mapper.createObjectNode();
if (!params.isObject()) { send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid parameters")); return; }
if (rpc.equals("initialize")) {
if (id.isMissingNode() || initialized != null || !params.path("protocolVersion").isTextual()
|| !params.path("capabilities").isObject() || !params.path("clientInfo").isObject()
|| !params.path("clientInfo").path("name").isTextual() || !params.path("clientInfo").path("version").isTextual()) {
send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return;
}
synchronized (sessions) {
if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; }
sessionId = secret(); sessions.put(sessionId, new AtomicBoolean());
}
exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId);
var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION);
result.putObject("capabilities").putObject("tools").put("listChanged", false);
result.putObject("serverInfo").put("name", "prometeu-studio-mcp").put("version", "1.0");
result.put("instructions", McpConnectionGuide.INSTRUCTIONS);
send(exchange, 200, response(id, result)); return;
}
if (initialized == null) { empty(exchange, 400); return; }
if (id.isMissingNode()) {
if (rpc.equals("notifications/initialized")) initialized.set(true);
// Notifications do not implicitly cancel an already returned operationId or release authority.
empty(exchange, 202); return;
}
if (!initialized.get() && !rpc.equals("ping")) { send(exchange, 200, error(id, -32600, "Initialization required")); return; }
try {
JsonNode result = switch (rpc) {
case "ping" -> mapper.createObjectNode();
case "tools/list" -> {
if (params.has("cursor")) throw new IllegalArgumentException("No further tool page");
yield mapper.createObjectNode().set("tools", tools.descriptors());
}
case "tools/call" -> {
if (!params.path("name").isTextual()) throw new IllegalArgumentException("Missing tool name");
yield tools.call(params.get("name").asText(), params.get("arguments")).wire();
}
default -> null;
};
send(exchange, 200, result == null ? error(id, -32601, "Method not found") : response(id, result));
} catch (IllegalArgumentException invalid) { send(exchange, 200, error(id, -32602, "Invalid tool or parameters")); }
catch (RuntimeException failure) { send(exchange, 200, error(id, -32603, "Internal error")); }
} finally { timeout.cancel(false); }
}
private String secret() { byte[] bytes = new byte[32]; random.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); }
private static String single(Headers headers, String name) {
var values = headers.get(name);
return values == null ? null : values.size() == 1 ? values.getFirst() : "<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,50 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.api.automation.AgentConnectionGuide;
import p.studio.api.operation.OperationSubscription;
import p.studio.core.project.ProjectAccessRegistry;
import java.nio.file.Path;
import java.util.Optional;
/** Builds a provider-neutral connection descriptor from the live server, only on explicit export. */
public final class McpConnectionGuide implements AgentConnectionGuide {
public static final String INSTRUCTIONS = """
Configure your external coding client's MCP connection using the url and Authorization header below.
This is a provider-neutral descriptor, not a provider-specific configuration file.
Keep the token private; do not commit this descriptor, write it into project files or include it in logs.
Connect and list available tools. Read studio_project_context for the explicit projectRoot and consult
studio_reference_read for the declared languages, SDK and libraries before editing as needed.
Do not assume PBS or another language when support/documentation is missing; report the limitation.
Wait for the developer to grant control in DEV, then call studio_control_acquire. Copying or connecting
does not grant permission. Use the returned taskId for all work and operate only on this project.
Edit saved project files with your native tools; SDK and external libraries are read-only.
Validate saved changes with studio_language_query and studio_build_start. Poll studio_operation_get.
Supply a unique clientRequestId per intended build/advance. Recover lost responses by lookup using
clientRequestId; do not blindly repeat frame advancement with a new ID. Cancellation acknowledgement
is not worker termination. Use only tools/capabilities actually advertised by this running Studio.
Observe headless images/state when those tools are available, and explicitly studio_control_release
when finished. On revocation stop external edits too: Studio cannot stop your native file writes.
Existing edits are preserved. Git/review/recovery remain the developer's responsibility.
Recopy and update your client's connection after Studio restart: endpoint and token are ephemeral.
""";
private final LocalMcpServer server;
private final ProjectAccessRegistry projects;
private final ObjectMapper mapper;
public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper) {
this.server = server; this.projects = projects; this.mapper = mapper;
}
@Override public Optional<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);
var live = server.connection();
var value = mapper.createObjectNode().put("transport", "streamable-http").put("url", live.endpoint().toString());
value.putObject("headers").put("Authorization", live.authorizationHeader());
value.put("projectRoot", canonical.toString()).put("instructions", INSTRUCTIONS);
return value.toPrettyString();
}
@Override public OperationSubscription subscribe(Runnable changed) { return server.onConnectionChanged(changed); }
}
@@ -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,39 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.*;
/** Packaged v1 contract, not a claim that every provider has been composed. */
public final class McpToolCatalog {
private final Map<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 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,43 @@
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 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,174 @@
package p.studio.app.operation;
import p.studio.api.operation.OperationExecutor;
import p.studio.api.operation.OperationHandle;
import p.studio.api.operation.OperationId;
import p.studio.api.operation.OperationSnapshot;
import p.studio.api.operation.OperationState;
import p.studio.api.operation.OperationSubscription;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
public final class ExecutorOperationExecutor implements OperationExecutor {
private final ExecutorService executor;
public ExecutorOperationExecutor(ExecutorService executor) {
this.executor = Objects.requireNonNull(executor, "executor");
}
@Override
public <R> OperationHandle<R> submit(String summary, Callable<R> operation) {
final ExecutorOperationHandle<R> handle = new ExecutorOperationHandle<>(summary, operation);
handle.start(executor);
return handle;
}
private static final class ExecutorOperationHandle<R> implements OperationHandle<R> {
private final OperationId id = new OperationId(UUID.randomUUID().toString());
private final String summary;
private final Callable<R> operation;
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 AtomicReference<OperationSnapshot> snapshot;
private volatile Future<?> task;
private ExecutorOperationHandle(String summary, Callable<R> operation) {
this.summary = Objects.requireNonNullElse(summary, "");
this.operation = Objects.requireNonNull(operation, "operation");
this.snapshot = new AtomicReference<>(new OperationSnapshot(id, OperationState.PENDING, Instant.now(), this.summary));
}
private void start(ExecutorService executor) {
final FutureTask<Void> submitted = new FutureTask<>(() -> {
try {
final R result = operation.call();
if (transitionTerminal(OperationState.SUCCEEDED, summary)) {
completion.complete(result);
}
} catch (Throwable failure) {
if (transitionTerminal(OperationState.FAILED, failureSummary(failure))) {
completion.completeExceptionally(failure);
}
}
return null;
}) {
@Override public void run() {
synchronized (workerLifecycle) { started = true; }
try { super.run(); }
finally { termination.complete(null); }
}
};
task = submitted;
try {
transition(OperationState.RUNNING, summary);
executor.execute(submitted);
} catch (RuntimeException failure) {
termination.complete(null);
if (transitionTerminal(OperationState.FAILED, failureSummary(failure))) {
completion.completeExceptionally(failure);
}
}
}
@Override
public OperationId id() {
return id;
}
@Override
public OperationSnapshot snapshot() {
return snapshot.get();
}
@Override
public CompletionStage<R> completion() {
return completion;
}
@Override public CompletionStage<Void> termination() { return termination; }
@Override
public boolean cancel() {
while (true) {
final OperationSnapshot current = snapshot.get();
if (terminal(current.state())) {
return false;
}
final OperationSnapshot cancelled = new OperationSnapshot(id, OperationState.CANCELLED, Instant.now(), summary);
if (snapshot.compareAndSet(current, cancelled)) {
final Future<?> submitted = task;
synchronized (workerLifecycle) {
if (submitted != null) submitted.cancel(true);
if (!started) termination.complete(null);
}
completion.cancel(false);
publish(cancelled);
return true;
}
}
}
@Override
public OperationSubscription subscribe(Consumer<OperationSnapshot> subscriber) {
final Consumer<OperationSnapshot> listener = Objects.requireNonNull(subscriber, "subscriber");
subscribers.add(listener);
notifySubscriber(listener, snapshot.get());
return () -> subscribers.remove(listener);
}
private void transition(OperationState state, String message) {
final OperationSnapshot next = new OperationSnapshot(id, state, Instant.now(), message);
snapshot.set(next);
publish(next);
}
private boolean transitionTerminal(OperationState state, String message) {
while (true) {
final OperationSnapshot current = snapshot.get();
if (terminal(current.state())) {
return false;
}
final OperationSnapshot next = new OperationSnapshot(id, state, Instant.now(), message);
if (snapshot.compareAndSet(current, next)) {
publish(next);
return true;
}
}
}
private void publish(OperationSnapshot value) {
subscribers.forEach(subscriber -> notifySubscriber(subscriber, value));
}
private static void notifySubscriber(Consumer<OperationSnapshot> subscriber, OperationSnapshot value) {
try {
subscriber.accept(value);
} catch (RuntimeException ignored) {
// Observation must not change operation completion.
}
}
private static boolean terminal(OperationState state) {
return state == OperationState.SUCCEEDED || state == OperationState.FAILED || state == OperationState.CANCELLED;
}
private String failureSummary(Throwable failure) {
final String message = failure.getMessage();
return message == null || message.isBlank() ? summary : message;
}
}
}
@@ -0,0 +1,159 @@
package p.studio.app.runtime;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.api.project.ProjectLocalStudioSetup;
import p.studio.api.project.ProjectReference;
import p.studio.api.runtime.RuntimeLogEntry;
import p.studio.core.runtime.RuntimeConnection;
import p.studio.core.runtime.RuntimeGateway;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
public final class ExternalRuntimeGateway implements RuntimeGateway {
private static final int DEBUG_PORT = 7777;
private final ObjectMapper mapper;
private final Executor executor;
public ExternalRuntimeGateway(ObjectMapper mapper, Executor executor) {
this.mapper = Objects.requireNonNull(mapper, "mapper");
this.executor = Objects.requireNonNull(executor, "executor");
}
@Override
public RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup,
Consumer<RuntimeLogEntry> logs) throws Exception {
final Consumer<RuntimeLogEntry> sink = Objects.requireNonNull(logs, "logs");
final Path executable = resolveExecutable(setup);
final Process process = new ProcessBuilder(executable.toString(), "debug", "build")
.directory(project.rootPath().toFile()).start();
stream(process.getInputStream(), false, sink);
stream(process.getErrorStream(), true, sink);
try {
final Socket socket = connectWithRetry();
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
final JsonNode handshake = mapper.readTree(requireLine(reader, "connection closed during handshake"));
if (handshake == null || !"handshake".equals(handshake.path("type").asText())) {
throw new IOException("invalid runtime handshake");
}
writer.write("{\"type\":\"start\"}");
writer.newLine();
writer.flush();
sink.accept(RuntimeLogEntry.info("Runtime protocol %d (%s)".formatted(
handshake.path("protocol_version").asInt(), handshake.path("runtime_version").asText("unknown"))));
final var connection = new ProcessRuntimeConnection(process, socket, reader, writer);
executor.execute(() -> receive(reader, sink, connection));
return connection;
} catch (Exception failure) {
process.descendants().forEach(ProcessHandle::destroyForcibly);
process.destroyForcibly();
throw failure;
}
}
private static Path resolveExecutable(ProjectLocalStudioSetup setup) throws IOException {
if (setup.prometeuRuntimePath() == null) throw new IOException("prometeuRuntimePath is missing");
final Path executable = Path.of(setup.prometeuRuntimePath()).resolve("prometeu").toAbsolutePath().normalize();
if (!Files.isRegularFile(executable)) throw new IOException("runtime not found at " + executable);
if (!Files.isExecutable(executable)) throw new IOException("runtime is not executable at " + executable);
return executable;
}
private Socket connectWithRetry() throws IOException {
IOException failure = null;
for (int attempt = 0; attempt < 20; attempt++) {
final Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress("127.0.0.1", DEBUG_PORT), 500);
socket.setSoTimeout(5_000);
return socket;
} catch (IOException exception) {
failure = exception;
closeQuietly(socket);
try { Thread.sleep(100L); } catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IOException("runtime connection interrupted", interrupted);
}
}
}
throw failure == null ? new IOException("runtime connection failed") : failure;
}
private void stream(InputStream stream, boolean error, Consumer<RuntimeLogEntry> sink) {
executor.execute(() -> {
try (var reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) sink.accept(error ? RuntimeLogEntry.error(line) : RuntimeLogEntry.info(line));
} catch (IOException ignored) { }
});
}
private void receive(BufferedReader reader, Consumer<RuntimeLogEntry> sink, ProcessRuntimeConnection connection) {
try {
String line;
while ((line = reader.readLine()) != null) {
final JsonNode event = mapper.readTree(line);
if (event != null && "log".equals(event.path("event").asText())) {
final String source = event.path("source").asText("");
final String message = event.path("msg").asText("");
final String rendered = source.isBlank() ? message : "[" + source + "] " + message;
final boolean error = switch (event.path("level").asText("").toUpperCase()) {
case "ERROR", "FATAL" -> true;
default -> false;
};
sink.accept(error ? RuntimeLogEntry.error(rendered) : RuntimeLogEntry.info(rendered));
}
}
} catch (IOException failure) {
if (!connection.closed) sink.accept(RuntimeLogEntry.error("Runtime debug connection lost: " + failure.getMessage()));
}
}
private static String requireLine(BufferedReader reader, String message) throws IOException {
final String line = reader.readLine();
if (line == null) throw new IOException(message);
return line;
}
private static void closeQuietly(Closeable closeable) {
if (closeable == null) return;
try { closeable.close(); } catch (IOException ignored) { }
}
private static final class ProcessRuntimeConnection implements RuntimeConnection {
private final Process process;
private final Socket socket;
private final Reader reader;
private final Writer writer;
private volatile boolean closed;
private ProcessRuntimeConnection(Process process, Socket socket, Reader reader, Writer writer) {
this.process = process;
this.socket = socket;
this.reader = reader;
this.writer = writer;
}
@Override public CompletableFuture<Integer> completion() { return process.onExit().thenApply(Process::exitValue); }
@Override public void close() {
if (closed) return;
closed = true;
closeQuietly(reader);
closeQuietly(writer);
closeQuietly(socket);
process.descendants().forEach(ProcessHandle::destroyForcibly);
process.destroyForcibly();
}
}
}
@@ -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,318 @@
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);
item.result.completeExceptionally(new AutomationException(code, "Runtime " + error.path("code").asText() + ": " + error.path("message").asText()));
} else {
var result = message.get("result");
if (item.command.equals("cancel") && (!result.path("requested").isBoolean() || !result.path("requested").booleanValue()
|| !result.path("targetRequestId").equals(item.params.path("targetRequestId")))) throw invalid("Invalid cancellation acknowledgement");
pending.remove(item.id); item.result.complete(result);
}
}
private void readErrors() {
try (var input = process.getErrorStream()) {
byte[] bytes = new byte[1024]; int read;
while ((read = input.read(bytes)) != -1) synchronized (stderr) {
stderr.addLast(new String(bytes, 0, read, StandardCharsets.UTF_8));
while (stderr.size() > 32) stderr.removeFirst();
}
} catch (IOException ignored) { }
}
void abort(String message) {
if (dead.compareAndSet(false, true)) {
terminate();
greeting.completeExceptionally(infrastructure(message));
pending.values().forEach(item -> item.result.completeExceptionally(infrastructure(message))); pending.clear();
} else terminate();
}
private void terminate() {
dead.set(true);
process.descendants().forEach(descendants::add);
descendants.forEach(ProcessHandle::destroyForcibly); process.destroyForcibly();
writer.shutdownNow(); timer.shutdownNow(); io.shutdown();
// Killing first unblocks pipe IO; closing a writer before kill can wait on its blocked monitor.
try { process.waitFor(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
descendants.forEach(handle -> { if (handle.isAlive()) handle.destroyForcibly(); });
for (var handle : descendants) {
try { handle.onExit().get(1000, TimeUnit.MILLISECONDS); }
catch (Exception ignored) { /* A failed cleanup is surfaced by shutdown below. */ }
}
if (!process.isAlive()) {
try { process.getOutputStream().close(); } catch (IOException ignored) { }
}
}
private void invalidateMalformed(AutomationException failure) {
if (failure.getMessage().startsWith("Invalid headless response:")) abort("Invalid headless response");
}
private static AutomationException infrastructure(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, message); }
private static <T> 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,201 @@
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);
}
@Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception {
var pool = Executors.newSingleThreadExecutor();
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
var subscriptions = new AtomicInteger();
var observed = (AutomationSession) java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[]{AutomationSession.class}, (proxy, method, args) -> {
var result = method.invoke(authority, args);
if (method.getName().equals("subscribe")) {
subscriptions.incrementAndGet();
return (OperationSubscription) () -> { ((OperationSubscription) result).unsubscribe(); subscriptions.decrementAndGet(); };
}
return result;
});
var stage = new Stage[1]; var host = new WorkspaceHost[1]; var dev = new DevWorkspace[1];
var locale = new I18nService();
try {
fx(() -> {
var project = new ProjectReference("DEV smoke", "1", "pbs", 1, ProjectTarget.Game, root);
var events = new StudioEventBus();
host[0] = new WorkspaceHost();
dev[0] = new DevWorkspace(project, observed, locale, events);
host[0].register(dev[0]);
host[0].register(new DebugWorkspace(project, new DefaultExecutionSession(), locale, events));
stage[0] = new Stage(); stage[0].setTitle("DEV/Debug desktop verification");
stage[0].setScene(new Scene(host[0], 1050, 800)); stage[0].show(); host[0].change(WorkspaceId.DEV);
});
fx(() -> {
assertEquals(1, subscriptions.get());
assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled());
((Button) dev[0].rootNode().lookup("#dev-grant")).fire();
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get());
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
host[0].change(WorkspaceId.DEV);
});
fx(() -> assertEquals(1, subscriptions.get()));
var task = authority.acquire(); // Intentionally outside the FX thread.
authority.attachRuntime(task.task(), new ManagedHeadlessSession() {
public String sessionId() { return "smoke-session"; }
public void cancel() { }
public CompletionStage<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);
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
});
} finally {
fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); });
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow();
}
}
@Test void formsSaveFailurePreservesDraftAndReturnReadsExternalContent() throws Exception {
var file = root.resolve("document.txt"); Files.writeString(file, "initial");
fx(() -> {
var form = new TestForm(); form.draft = "edited"; form.dirty = true;
form.fail = true;
assertThrows(CompletionException.class, () -> form.saveForHandoff().toCompletableFuture().join());
assertTrue(form.hasUnsavedDraft()); assertEquals("edited", form.draft);
form.fail = false; form.saveForHandoff().toCompletableFuture().join(); assertFalse(form.hasUnsavedDraft());
form.draft = "stale presentation";
try { Files.writeString(file, "external agent edit"); } catch (Exception failure) { throw new RuntimeException(failure); }
form.discardDraftForHandoff();
try { form.draft = Files.readString(file); } catch (Exception failure) { throw new RuntimeException(failure); }
assertEquals("external agent edit", form.draft);
});
}
@Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception {
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
var projects = new p.studio.core.project.ProjectAccessRegistry();
var savedClipboard = new java.util.HashMap<javafx.scene.input.DataFormat, Object>();
var copied = new java.util.concurrent.atomic.AtomicReference<String>();
var view = new DevWorkspace[1]; var stage = new Stage[1];
try (var pool = Executors.newSingleThreadExecutor();
var server = new p.studio.app.mcp.LocalMcpServer(mapper, new p.studio.app.mcp.McpToolRegistry(
new p.studio.app.mcp.McpToolCatalog(mapper), mapper, java.util.Map.of()))) {
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority);
var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper);
server.start();
try {
fx(() -> {
var clipboard = javafx.scene.input.Clipboard.getSystemClipboard();
clipboard.getContentTypes().forEach(type -> savedClipboard.put(type, clipboard.getContent(type)));
var project = new ProjectReference("Connection smoke", "1", "pbs", 1, ProjectTarget.Game, root);
view[0] = new DevWorkspace(project, authority, new I18nService(), new StudioEventBus(), guide);
stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show();
view[0].load();
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled());
button.fire(); copied.set(clipboard.getString());
assertEquals(ControlState.MANUAL, authority.snapshot().state());
assertEquals(server.connection().endpoint().toString(), ((Label) view[0].rootNode().lookup("#dev-mcp-endpoint")).getText());
assertTrue(view[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label)
.noneMatch(n -> ((Label) n).getText().contains(server.connection().authorizationHeader())));
});
var first = mapper.readTree(copied.get());
assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText()));
assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText());
server.close();
fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
server.start(); authority.grant(false).toCompletableFuture().join();
fx(() -> {
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled());
button.fire(); copied.set(javafx.scene.input.Clipboard.getSystemClipboard().getString());
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
});
var next = mapper.readTree(copied.get());
assertFalse(first.path("headers").equals(next.path("headers")));
assertTrue(server.connection().authorizationHeader().equals(next.path("headers").path("Authorization").asText()));
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
} finally {
fx(() -> {
if (view[0] != null) view[0].unLoad();
if (stage[0] != null) stage[0].close();
javafx.scene.input.Clipboard.getSystemClipboard().setContent(savedClipboard);
});
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close();
}
}
}
@Test void lockedUiBlocksMutationActionsButNotReadOnlyActions() throws Exception {
fx(() -> {
var root = new VBox(); var mutate = new Button("write"); var inspect = new Button("inspect");
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 = ""; }
}
}
@@ -0,0 +1,44 @@
package p.studio.app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import p.packer.PackerWorkspaceService;
import p.studio.api.operation.OperationExecutor;
import java.util.concurrent.ExecutorService;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StudioApplicationConfigurationTest {
@Test
void bootsAndClosesWithoutAWebApplicationContext() {
final ConfigurableApplicationContext context = new SpringApplicationBuilder(StudioApplicationConfiguration.class)
.web(WebApplicationType.NONE)
.headless(true)
.run();
final ExecutorService executor = context.getBean(ExecutorService.class);
final var mcp = context.getBean(p.studio.app.mcp.LocalMcpServer.class);
try (context) {
assertNotNull(context.getBean(StudioUiFactory.class));
assertNotNull(context.getBean(PackerWorkspaceService.class));
assertNotNull(context.getBean(OperationExecutor.class));
assertFalse(context.getClass().getName().contains("WebServer"));
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
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());
assertFalse(mcp.isRunning());
}
}
@@ -0,0 +1,32 @@
package p.studio.app;
import org.junit.jupiter.api.Test;
import p.packer.events.PackerEvent;
import p.packer.events.PackerEventKind;
import p.packer.events.PackerProgress;
import p.studio.ui.javafx.events.StudioEventBus;
import p.studio.ui.javafx.events.StudioPackerOperationEvent;
import p.studio.ui.javafx.events.StudioPackerOperationKind;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
final class StudioPackerEventAdapterTest {
@Test
void translatesProviderEventsIntoStudioEvents() {
final StudioEventBus globalBus = new StudioEventBus();
final List<StudioPackerOperationEvent> events = new ArrayList<>();
globalBus.subscribe(StudioPackerOperationEvent.class, events::add);
new StudioPackerEventAdapter(globalBus).publish(new PackerEvent(
"main", "op-1", 0L, PackerEventKind.ASSET_DISCOVERED, Instant.now(),
"Discovered asset.", new PackerProgress(0.25d, false), List.of("ui_atlas")));
assertEquals(1, events.size());
assertEquals(StudioPackerOperationKind.ASSET_DISCOVERED, events.getFirst().kind());
assertEquals(0.25d, events.getFirst().progress());
}
}
@@ -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,18 @@
package p.studio.app.compiler;
import org.junit.jupiter.api.Test;
import p.studio.compiler.FrontendRegistryService;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CompilerProjectLanguageCatalogTest {
@Test
void listsLanguagesFromRegisteredProviders() {
FrontendRegistryService.bootstrapDefaults();
final var templates = new CompilerProjectLanguageCatalog().listLanguageTemplates();
assertEquals(1, templates.size());
assertEquals("pbs", templates.getFirst().languageId());
}
}
@@ -0,0 +1,62 @@
package p.studio.app.compiler;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.api.automation.ProjectKnowledge;
import p.studio.compiler.FrontendRegistryService;
import p.studio.compiler.messages.BuilderPipelineConfig;
import p.studio.compiler.models.BuilderPipelineContext;
import p.studio.compiler.workspaces.BuilderPipelineService;
import p.studio.core.project.*;
import p.studio.utilities.logs.LogAggregator;
import java.nio.file.Files;
import java.nio.file.Path;
/** Separate JVM gate: product classes/resources must resolve exclusively from installDist JARs. */
public final class InstalledKnowledgeProbe {
public static void main(String[] arguments) throws Exception {
var provider = FrontendRegistryService.require("pbs");
check(provider.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "Frontend must come from installed JAR");
check(CompilerProjectKnowledge.class.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "App must come from installed JAR");
check(!Files.exists(Path.of("settings.gradle.kts")) && !Files.exists(Path.of("docs")), "No repository in working directory");
Path root = Files.createDirectory(Path.of("example")).toRealPath();
var docs = provider.documentation().orElseThrow().references(1, p.studio.AppMode.Game);
for (var reference : docs) {
if (reference.id().startsWith("pbs:example:game:1:")) {
Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length()));
Files.createDirectories(file.getParent());
Files.writeString(file, reference.text());
}
}
var mapper = new ObjectMapper();
var access = new ProjectAccessRegistry();
var registration = access.register(root, () -> { throw new AssertionError("References require no grant"); }, () -> true);
var catalog = new ProjectCatalogService(root, mapper, new ProjectLocalStudioSetupStore(mapper));
var knowledge = new CompilerProjectKnowledge(access, catalog, mapper);
var context = knowledge.context(root);
for (var kind : java.util.List.of(ProjectKnowledge.ReferenceKind.QUICKSTART, ProjectKnowledge.ReferenceKind.SYNTAX,
ProjectKnowledge.ReferenceKind.SEMANTICS, ProjectKnowledge.ReferenceKind.EXAMPLE, ProjectKnowledge.ReferenceKind.SDK))
check(context.references().stream().anyMatch(ref -> ref.kind() == kind), "Missing " + kind);
for (var reference : docs) {
var actual = new StringBuilder();
int offset = 0;
while (true) {
var page = knowledge.readReference(root, reference.id(), offset, 997);
actual.append(page.text());
if (page.nextOffset() == null) break;
offset = page.nextOffset();
}
check(actual.toString().equals(reference.text()), "Incorrect installed reference: " + reference.id());
}
var result = BuilderPipelineService.INSTANCE.compile(
BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), LogAggregator.empty());
check(result.diagnostics().stream().noneMatch(issue -> issue.isError()), "Example must compile without errors");
check(result.bytecodeBytes().length > 0, "Example must produce bytecode");
registration.unsubscribe();
System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled");
}
private static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
@@ -0,0 +1,33 @@
package p.studio.app.compiler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
class InstalledKnowledgeTest {
@TempDir Path outsideRepository;
@Test void installedJarsProvideAllReferencesAndCompileTheExampleOutsideTheCheckout() throws Exception {
Path distribution = Path.of(System.getProperty("studio.test.distribution"));
String jars;
try (var files = Files.list(distribution.resolve("lib"))) {
jars = files.filter(file -> file.toString().endsWith(".jar")).sorted()
.map(Path::toString).collect(Collectors.joining(java.io.File.pathSeparator));
}
String probeClasses = Path.of(InstalledKnowledgeProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
Path output = outsideRepository.resolve("probe.log");
var process = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "java").toString(),
"-cp", jars + java.io.File.pathSeparator + probeClasses, InstalledKnowledgeProbe.class.getName())
.directory(outsideRepository.toFile()).redirectErrorStream(true).redirectOutput(output.toFile()).start();
try {
assertTrue(process.waitFor(45, TimeUnit.SECONDS), "Installed knowledge probe timed out");
String log = Files.readString(output);
assertEquals(0, process.exitValue(), log);
assertTrue(log.contains("references; example compiled"), log);
} finally { if (process.isAlive()) process.destroyForcibly().waitFor(); }
}
}
@@ -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,210 @@
package p.studio.app.lsp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.automation.*;
import p.studio.api.session.ProjectSession;
import p.studio.app.compiler.CompilerProjectKnowledge;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.core.language.TaskLanguageQueries;
import p.studio.core.project.*;
import p.studio.core.session.DefaultProjectSessionFactory;
import p.studio.lsp.services.LspServerLifecycleImpl;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
class AutomationLspQueriesTest {
@TempDir Path temporary;
final ObjectMapper mapper = new ObjectMapper();
final ExecutorService workers = Executors.newCachedThreadPool();
final LspServerLifecycleImpl lifecycle = new LspServerLifecycleImpl();
ProjectSession session;
TaskLanguageQueries queries;
final ProjectAccessRegistry access = new ProjectAccessRegistry();
Path root, source;
String task;
static final String CODE = "fn helper() -> int { return 1; }\nfn main() -> int { return helper(); }\n";
@BeforeEach void open() throws Exception {
root = Files.createDirectory(temporary.resolve("app")).toRealPath();
source = Files.createDirectories(root.resolve("src")).resolve("main.pbs");
manifest(root, "app", List.of());
Files.writeString(source, CODE);
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn helper() -> int;\npub fn main() -> int;\n");
var setup = new ProjectLocalStudioSetupStore(mapper);
var catalog = new ProjectCatalogService(temporary, mapper, setup);
session = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup,
new LspLifecycleAdapter(lifecycle), access, new ExecutorOperationExecutor(workers)).open(catalog.openProject(root));
var knowledge = new CompilerProjectKnowledge(access, catalog, mapper);
queries = new TaskLanguageQueries(access, new AutomationLspQueries(lifecycle, catalog, knowledge, mapper));
}
@AfterEach void close() { if (session != null) session.close(); workers.shutdownNow(); }
void acquire() {
assertTrue(session.automation().grant(false).toCompletableFuture().join().success());
task = session.automation().acquire().task().value();
}
JsonNode query(String operation, Map<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 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 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", server.connection().authorizationHeader()).header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
if (connection != null) request.header("Mcp-Session-Id", connection);
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
}
@Test void reclaimCancelsTheQueryAndEndsTaskResourcesAfterTheWorkerStops() throws Exception {
var entered = new CountDownLatch(1);
var stopped = new CountDownLatch(1);
var cleaned = new java.util.concurrent.atomic.AtomicBoolean();
var slow = new TaskLanguageQueries(access, new p.studio.core.language.LanguageQueryPort() {
@Override public Map<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());
}
@Test void externalDependencyNavigationIsReadableButRefactoringIsReadOnly() throws Exception {
Path lib = Files.createDirectories(temporary.resolve("lib")).toRealPath();
manifest(lib, "lib", List.of());
Path module = Files.createDirectories(lib.resolve("src/shared"));
Path declaration = module.resolve("main.pbs");
Files.writeString(declaration, "fn answer() -> int { return 42; }\n");
Files.writeString(module.resolve("mod.barrel"), "pub fn answer() -> int;\n");
manifest(root, "app", List.of(Map.of("path", "../lib")));
Files.createDirectories(root.resolve(".workspace/repos")); Files.writeString(root.resolve(".workspace/repos/registry.json"), "{}");
Files.writeString(source, "import { answer } from @lib:shared;\nfn main() -> int { return answer(); }\n");
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn main() -> int;\n");
acquire();
var locations = query("definition", at(1, 26)).path("result");
assertFalse(locations.isEmpty(), locations.toString());
assertEquals(declaration.toUri().toString(), locations.get(0).path("uri").asText());
assertEquals("documentSymbols", query("documentSymbols", Map.of("uri", declaration.toUri().toString())).path("operation").asText());
assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class,
() -> query("formatting", Map.of("uri", declaration.toUri().toString()))).failure().code());
var rename = new HashMap<>(at(1, 26)); rename.put("newName", "renamed");
assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class, () -> query("rename", rename)).failure().code());
}
private void manifest(Path path, String name, List<?> dependencies) throws Exception {
mapper.writeValue(path.resolve("prometeu.json").toFile(), Map.of("name", name, "version", "1.0.0", "language", "pbs", "stdlib", "1", "target", "Game", "dependencies", dependencies));
}
}
@@ -0,0 +1,179 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import p.studio.api.automation.*;
import static org.junit.jupiter.api.Assertions.*;
class LocalMcpServerTest {
final ObjectMapper mapper = new ObjectMapper();
final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
LocalMcpServer server;
String session;
AtomicInteger calls;
@BeforeEach void start() throws Exception {
calls = new AtomicInteger();
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of(
"studio_project_context", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("projectRoot", args.get("projectRoot").asText())); },
"studio_control_acquire", args -> McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.NOT_GRANTED, "Human grant required")))));
server.start();
}
@AfterEach void close() { server.close(); client.close(); }
HttpResponse<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, server.connection().authorizationHeader(), null, LocalMcpServer.PROTOCOL_VERSION, session);
}
static String init() { return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1\"},\"capabilities\":{}}}"; }
void initialize() throws Exception {
var response = post(init()); assertEquals(200, response.statusCode());
session = response.headers().firstValue("Mcp-Session-Id").orElseThrow();
assertEquals(LocalMcpServer.PROTOCOL_VERSION, mapper.readTree(response.body()).path("result").path("protocolVersion").asText());
assertEquals(202, post("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}").statusCode());
}
@Test void lifecycleNegotiatesListsAndCallsOnlyActualHandlers() throws Exception {
initialize();
var listed = mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}").body());
assertEquals(2, listed.path("result").path("tools").size());
var response = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
assertEquals(200, response.statusCode()); assertEquals(1, calls.get());
assertEquals("ok", mapper.readTree(response.body()).path("result").path("structuredContent").path("status").asText());
assertEquals(200, request("DELETE", server.connection().endpoint(), null, server.connection().authorizationHeader(), null, null, session).statusCode());
assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode());
}
@Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception {
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0);
assertEquals(401, request("POST", endpoint, init(), null, null, null, null).statusCode());
assertEquals(401, request("POST", endpoint, init(), "Bearer wrong", null, null, null).statusCode());
for (var origin : List.of("null", "https://evil.example", "http://127.0.0.1:1", "http://localhost:" + endpoint.getPort()))
assertEquals(403, request("POST", endpoint, init(), token, origin, null, null).statusCode());
assertEquals(200, request("POST", endpoint, init(), token, "http://" + endpoint.getRawAuthority(), null, null).statusCode());
assertEquals(0, calls.get());
assertFalse(server.connection().toString().contains(token.substring(7)));
}
@Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception {
initialize(); var old = server.connection(); server.close();
assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection);
server.start(); assertFalse(old.authorizationHeader().equals(server.connection().authorizationHeader()));
assertEquals(401, request("POST", server.connection().endpoint(), init(), old.authorizationHeader(), null, null, null).statusCode());
assertEquals(404, post(init()).statusCode());
session = null; initialize();
}
@Test void malformedBodiesVersionsAndToolsCannotReachProviders() throws Exception {
initialize();
assertEquals(400, post("{not json}").statusCode());
assertEquals(400, post("[]").statusCode());
assertEquals(400, post("{\"jsonrpc\":2.0,\"id\":1,\"method\":\"ping\"}").statusCode());
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"method\":123}").statusCode());
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"id\":2,\"method\":\"ping\"}").statusCode());
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"} {}").statusCode());
assertEquals(400, request("POST", server.connection().endpoint(), init(), server.connection().authorizationHeader(), null, "unknown", session).statusCode());
var bad = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"relative\"}}}");
assertEquals(-32602, mapper.readTree(bad.body()).path("error").path("code").intValue()); assertEquals(0, calls.get());
assertEquals(413, post(" ".repeat(1024 * 1024 + 1)).statusCode());
}
@Test void exactEndpointNoSseAndInitializationAreEnforced() throws Exception {
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").statusCode());
var initialized = post(init()); session = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow();
assertEquals(-32600, mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").body()).path("error").path("code").asInt());
assertEquals(405, request("GET", endpoint, null, token, null, null, session).statusCode());
assertEquals(404, request("POST", URI.create(endpoint + "/nested"), init(), token, null, null, null).statusCode());
assertEquals(404, request("POST", URI.create(endpoint + "?token=forbidden"), init(), token, null, null, null).statusCode());
assertEquals(0, calls.get());
}
@Test void authenticatedConnectionDoesNotGrantControl() throws Exception {
initialize();
var denied = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_control_acquire\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
var result = mapper.readTree(denied.body()).path("result");
assertTrue(result.path("isError").asBoolean()); assertEquals("NOT_GRANTED", result.path("structuredContent").path("error").path("code").asText());
}
@Test void realContextHandlerReadsAnOpenProjectWithoutGrantAndRejectsItAfterClose(
@org.junit.jupiter.api.io.TempDir java.nio.file.Path temporary) throws Exception {
var root = temporary.toRealPath();
java.nio.file.Files.writeString(root.resolve("prometeu.json"), """
{"name":"HTTP context","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
var open = new p.studio.core.project.ProjectAccessRegistry();
var registration = open.register(root, () -> { throw new AssertionError("Context must not acquire manual control"); }, () -> true);
var catalog = new p.studio.core.project.ProjectCatalogService(root, mapper,
new p.studio.core.project.ProjectLocalStudioSetupStore(mapper));
var knowledge = new p.studio.app.compiler.CompilerProjectKnowledge(open, catalog, mapper);
server.close();
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper,
McpProjectKnowledgeTools.handlers(knowledge, mapper)));
server.start();
initialize();
var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call");
call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", root.toString());
var wire = mapper.readTree(post(call.toString()).body()).path("result");
assertFalse(wire.path("isError").asBoolean());
var value = wire.path("structuredContent").path("value");
assertEquals(root.toString(), value.path("projectRoot").asText());
assertEquals(root.toString(), value.path("editableRoots").get(0).asText());
assertEquals("pbs", value.path("languages").get(0).path("id").asText());
assertTrue(value.path("languages").get(0).path("languageVersion").path("value").isNull());
assertFalse(java.nio.file.Files.exists(root.resolve(".studio")));
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: " + connection.authorizationHeader()
+ "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
socket.getOutputStream().write(request.getBytes(java.nio.charset.StandardCharsets.UTF_8));
var status = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())).readLine();
assertTrue(status.contains("403"));
}
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
.header("Origin", "http://" + connection.endpoint().getRawAuthority()).header("Origin", "https://evil.example")
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
assertEquals(403, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
}
@Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception {
var connection = server.connection();
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
.header("Accept", "application/json;q=1, text/event-stream;q=0.5").header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
assertEquals(200, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
.header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofByteArray(new byte[]{(byte) 0xc3, (byte) 0x28})).build();
assertEquals(400, client.send(invalid, HttpResponse.BodyHandlers.discarding()).statusCode());
}
}
@@ -0,0 +1,52 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.core.project.ProjectAccessRegistry;
import p.studio.core.session.DefaultAutomationSession;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.api.automation.*;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class McpConnectionGuideTest {
@TempDir Path root;
@Test void exportsLiveProjectDescriptorWithoutGrantAndTracksRestartWithoutRetainingSecrets() throws Exception {
var mapper = new ObjectMapper(); var projects = new ProjectAccessRegistry();
try (var workers = Executors.newSingleThreadExecutor();
var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) {
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers));
var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority);
var guide = new McpConnectionGuide(server, projects, mapper);
assertTrue(guide.endpoint().isEmpty());
assertThrows(IllegalStateException.class, () -> guide.configuration(root));
var notifications = new AtomicInteger();
var subscription = guide.subscribe(notifications::incrementAndGet);
server.start(); assertEquals(2, notifications.get());
var descriptor = mapper.readTree(guide.configuration(root));
assertEquals(server.connection().endpoint().toString(), descriptor.path("url").asText());
assertEquals(root.toRealPath().toString(), descriptor.path("projectRoot").asText());
// Do not put bearer credentials into assertion diagnostics.
assertTrue(server.connection().authorizationHeader().equals(descriptor.path("headers").path("Authorization").asText()));
assertFalse(guide.toString().contains(descriptor.path("headers").path("Authorization").asText()));
assertEquals(ControlState.MANUAL, authority.snapshot().state());
assertNull(authority.snapshot().task());
for (var instruction : List.of("studio_project_context", "studio_reference_read", "studio_control_acquire", "studio_control_release",
"studio_language_query", "studio_build_start", "clientRequestId", "read-only", "restart", "native file writes"))
assertTrue(descriptor.path("instructions").asText().contains(instruction));
var old = server.connection(); server.close(); assertEquals(3, notifications.get()); assertTrue(guide.endpoint().isEmpty());
server.start(); assertEquals(4, notifications.get());
var fresh = mapper.readTree(guide.configuration(root));
assertTrue(fresh.path("headers").path("Authorization").asText().equals(server.connection().authorizationHeader()));
assertFalse(fresh.path("headers").path("Authorization").asText().equals(old.authorizationHeader()));
assertThrows(AutomationException.class, () -> guide.configuration(root.resolve("unopened")));
authority.closeAsync().toCompletableFuture().join();
assertThrows(AutomationException.class, () -> guide.configuration(root));
registration.close(); subscription.close(); server.close(); assertEquals(4, notifications.get());
}
}
}
@@ -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,410 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.automation.*;
import p.studio.api.operation.*;
import p.studio.api.shipper.*;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.core.project.*;
import p.studio.core.runtime.HeadlessGateway;
import p.studio.core.session.*;
import p.studio.core.shipper.SavedProjectPreparation;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
class McpTaskToolsTest {
@TempDir Path root;
final ObjectMapper mapper = new ObjectMapper();
final ExecutorService workers = Executors.newCachedThreadPool();
final ProjectAccessRegistry access = new ProjectAccessRegistry();
final AtomicInteger builds = new AtomicInteger();
final CountDownLatch buildEntered = new CountDownLatch(1), buildGate = new CountDownLatch(1);
volatile boolean holdBuild, failBuild, infrastructureFailure;
DefaultAutomationSession session;
DefaultTaskTools service;
ProjectCatalogService catalog;
McpToolRegistry tools;
FakeRuntime runtime;
String task;
@BeforeEach void setup() throws Exception {
root = root.toRealPath();
Files.writeString(root.resolve("prometeu.json"), "{\"name\":\"game\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
catalog = new ProjectCatalogService(root.getParent(), mapper, new ProjectLocalStudioSetupStore(mapper));
session = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers));
access.register(root, session::enterManual, () -> !session.snapshot().closed(), session);
compose((project, sink) -> {
builds.incrementAndGet(); buildEntered.countDown();
if (holdBuild) awaitGate(buildGate);
if (infrastructureFailure) throw new IllegalStateException("test failure");
return failBuild ? ShipperPrepareResult.failed(List.of(), List.of("compile error"))
: new ShipperPrepareResult(ShipperPreparationStatus.SUCCESS, List.of(), root.resolve("build/manifest.json"), List.of(), List.of());
});
}
void compose(SavedProjectPreparation preparation) {
service = new DefaultTaskTools(access, catalog, preparation, Optional.of((project, buildId, build) -> {
runtime = new FakeRuntime(buildId); return runtime;
}));
tools = new McpToolRegistry(new McpToolCatalog(mapper), mapper, McpTaskTools.handlers(service, mapper, true));
}
@AfterEach void close() throws Exception {
buildGate.countDown();
if (runtime != null) { runtime.gate.countDown(); 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 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 unauthorized = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).POST(java.net.http.HttpRequest.BodyPublishers.ofString("{}"))
.timeout(java.time.Duration.ofSeconds(5)).build();
assertEquals(401, client.send(unauthorized, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
String first = connect(client, server), second = connect(client, server);
var list = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/list");
assertEquals(17, mapper.readTree(post(client, server, first, list).body()).path("result").path("tools").size());
var context = value(httpCall(client, server, first, "studio_project_context", rootOnly()));
assertTrue(context.path("languages").toString().contains("pbs"));
value(httpCall(client, server, first, "studio_reference_read", rootOnly().put("referenceId", "pbs:quickstart").put("limit", 100)));
error("NOT_GRANTED", httpCall(client, server, first, "studio_control_acquire", rootOnly()));
error("INVALID_TASK", httpCall(client, server, first, "studio_build_start", args().put("taskId", "missing").put("clientRequestId", "denied")));
session.grant(false).toCompletableFuture().join();
var a = workers.submit(() -> httpCall(client, server, first, "studio_control_acquire", rootOnly()));
var b = workers.submit(() -> httpCall(client, server, second, "studio_control_acquire", rootOnly()));
var results = List.of(a.get(5, TimeUnit.SECONDS), b.get(5, TimeUnit.SECONDS));
assertEquals(1, results.stream().filter(r -> !r.path("isError").asBoolean()).count());
task = value(results.stream().filter(r -> !r.path("isError").asBoolean()).findFirst().orElseThrow()).path("taskId").asText();
var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString());
value(httpCall(client, server, first, "studio_language_query", query));
Files.writeString(source, "fn main( {");
assertFalse(value(httpCall(client, server, first, "studio_language_query", query)).path("result").isEmpty());
Files.writeString(source, "fn main() -> int { return 2; }\n");
value(httpCall(client, server, first, "studio_language_query", query));
httpCall(client, server, first, "studio_build_start", args().put("clientRequestId", "conformance-build"));
var build = httpCompleted(client, server, first, "conformance-build");
value(httpCall(client, server, first, "studio_headless_boot", args().put("buildId", build.path("result").path("buildId").asText())));
for (var op : List.of("reset", "clear_input", "state", "fault")) value(httpCall(client, server, first, "studio_headless_" + op, args()));
value(httpCall(client, server, first, "studio_headless_set_input", args().set("input", mapper.createObjectNode().put("a", true))));
value(httpCall(client, server, first, "studio_headless_advance", args().put("clientRequestId", "conformance-advance").put("frames", 5)));
var advanced = httpCompleted(client, server, first, "conformance-advance");
assertEquals("SUCCEEDED", advanced.path("result").path("status").asText());
var captured = httpCall(client, server, first, "studio_headless_capture", args()); value(captured);
assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(captured.path("content").get(1).path("data").asText()));
var deleted = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", first).build();
assertEquals(200, client.send(deleted, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
String reconnected = connect(client, server);
assertEquals(advanced.path("operationId"), value(httpCall(client, server, reconnected, "studio_operation_get", args().put("clientRequestId", "conformance-advance"))).path("operationId"));
runtime.kind = AutomationOutcome.Kind.GUEST_FAULT;
value(httpCall(client, server, reconnected, "studio_headless_advance", args().put("clientRequestId", "guest").put("frames", 2)));
assertEquals("GUEST_FAULT", httpCompleted(client, server, reconnected, "guest").path("result").path("status").asText());
value(httpCall(client, server, reconnected, "studio_operation_cancel", args().put("operationId", advanced.path("operationId").asText())));
runtime.hold = true;
String pending = value(httpCall(client, server, reconnected, "studio_headless_advance",
args().put("clientRequestId", "cancel-over-http").put("frames", 50))).path("operationId").asText();
assertTrue(value(httpCall(client, server, reconnected, "studio_operation_cancel", args().put("operationId", pending)))
.path("cancellationRequested").asBoolean());
runtime.gate.countDown();
assertEquals("CANCELLED", httpCompleted(client, server, reconnected, "cancel-over-http").path("state").asText());
value(httpCall(client, server, reconnected, "studio_headless_shutdown", args()));
value(httpCall(client, server, reconnected, "studio_control_release", args()));
error("INVALID_TASK", httpCall(client, server, reconnected, "studio_operation_get", args().put("clientRequestId", "conformance-advance")));
session.grant(false).toCompletableFuture().join();
task = value(httpCall(client, server, reconnected, "studio_control_acquire", rootOnly())).path("taskId").asText();
session.reclaim().toCompletableFuture().join();
error("INVALID_TASK", httpCall(client, server, reconnected, "studio_build_start", args().put("clientRequestId", "late")));
} finally { lsp.shutdown(project); }
}
String connect(java.net.http.HttpClient client, LocalMcpServer server) throws Exception {
var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize");
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "conformance-test").put("version", "1");
String connection = post(client, server, null, initialize).headers().firstValue("Mcp-Session-Id").orElseThrow();
assertEquals(202, post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized")).statusCode());
return connection;
}
JsonNode httpCompleted(java.net.http.HttpClient client, LocalMcpServer server, String connection, String request) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
do {
var result = value(httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", request)));
if (result.path("workerTerminated").asBoolean()) return result;
Thread.sleep(5);
} while (System.nanoTime() < deadline);
throw new AssertionError("Operation did not terminate");
}
JsonNode httpCall(java.net.http.HttpClient client, LocalMcpServer server, String connection, String name, ObjectNode arguments) throws Exception {
var request = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", UUID.randomUUID().toString()).put("method", "tools/call");
request.putObject("params").put("name", name).set("arguments", arguments);
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", server.connection().authorizationHeader()).header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
if (connection != null) request.header("Mcp-Session-Id", connection);
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
}
static void awaitGate(CountDownLatch gate) {
boolean interrupted = false;
while (true) { try { gate.await(); break; } catch (InterruptedException ignored) { interrupted = true; } }
if (interrupted) Thread.currentThread().interrupt();
}
final class FakeRuntime implements HeadlessGateway.Session {
final String id = UUID.randomUUID().toString(), build;
final AtomicInteger advances = new AtomicInteger();
final CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1);
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,82 @@
package p.studio.app.operation;
import org.junit.jupiter.api.Test;
import p.studio.api.operation.OperationState;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
final class ExecutorOperationExecutorTest {
@Test
void cancellationDoesNotPretendAnUncooperativeWorkerHasStopped() throws Exception {
final var executor = Executors.newSingleThreadExecutor();
final var started = new CountDownLatch(1);
final var finish = new CountDownLatch(1);
try {
var handle = new ExecutorOperationExecutor(executor).submit("stubborn worker", () -> {
started.countDown();
boolean done = false;
while (!done) try { finish.await(); done = true; } catch (InterruptedException ignored) { }
return 42;
});
assertTrue(started.await(2, TimeUnit.SECONDS));
handle.cancel();
assertTrue(handle.completion().toCompletableFuture().isCancelled());
org.junit.jupiter.api.Assertions.assertFalse(handle.termination().toCompletableFuture().isDone());
finish.countDown();
handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS);
} finally { finish.countDown(); executor.shutdownNow(); }
}
@Test
void cancellingQueuedWorkCompletesTerminationWithoutRunningItsBody() throws Exception {
final var executor = Executors.newSingleThreadExecutor();
final var finish = new CountDownLatch(1);
try {
executor.submit(() -> { try { finish.await(); } catch (InterruptedException ignored) { } });
var handle = new ExecutorOperationExecutor(executor).submit("queued", () -> { throw new AssertionError("must not execute"); });
handle.cancel();
handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS);
} finally { finish.countDown(); executor.shutdownNow(); }
}
@Test
void completesWithTypedResultAndTerminalSnapshot() throws Exception {
final var executor = Executors.newSingleThreadExecutor();
try {
final var handle = new ExecutorOperationExecutor(executor).submit("test operation", () -> 42);
assertEquals(42, handle.completion().toCompletableFuture().get(2, TimeUnit.SECONDS));
assertEquals(OperationState.SUCCEEDED, handle.snapshot().state());
assertEquals("test operation", handle.snapshot().summary());
} finally {
executor.shutdownNow();
}
}
@Test
void cancellationInterruptsWorkAndCancelsCompletion() throws Exception {
final var executor = Executors.newSingleThreadExecutor();
final var started = new CountDownLatch(1);
try {
final var handle = new ExecutorOperationExecutor(executor).submit("cancel operation", () -> {
started.countDown();
new CountDownLatch(1).await();
return 42;
});
assertTrue(started.await(2, TimeUnit.SECONDS));
assertTrue(handle.cancel());
assertEquals(OperationState.CANCELLED, handle.snapshot().state());
assertThrows(java.util.concurrent.CancellationException.class,
() -> handle.completion().toCompletableFuture().join());
} finally {
executor.shutdownNow();
}
}
}
@@ -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,82 @@
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" -> 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,457 @@
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;
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();
});
connect();
}
void connect() throws Exception {
connection = null;
var initialize = request("initialize");
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "real-loop-test").put("version", "1");
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 acquire() throws Exception {
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
task = value(call("studio_control_acquire", args())).path("taskId").asText();
}
void prepareLongRun() throws Exception {
// Real guest work below the watchdog budget makes a 600-frame call observable in flight.
Files.writeString(source, Files.readString(source).replace("fn frame() -> void {",
"fn frame() -> void { let spin: int = 0; while (spin < 10000) { spin = spin + 1; }"));
acquire(); build("long-build"); boot();
}
JsonNode startRunning(String requestId) throws Exception {
var receipt = value(call("studio_headless_advance", args().put("clientRequestId", requestId).put("frames", 600)));
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
do {
var status = value(call("studio_operation_get", args().put("clientRequestId", requestId)));
assertFalse(status.path("workerTerminated").asBoolean(), status.toString());
if (status.path("progress").path("completedFrames").asInt() > 0) return receipt;
Thread.sleep(5);
} while (System.nanoTime() < deadline);
throw new AssertionError("No runtime progress");
}
@Test void disconnectAndDuplicateReceiptDoNotReplayAndCancellationRetainsTask() throws Exception {
prepareLongRun();
var receipt = startRunning("cancel-me");
var delete = HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", connection).build();
assertEquals(200, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode());
client.close(); client = HttpClient.newHttpClient(); connect();
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
assertEquals(receipt.path("operationId"), value(call("studio_headless_advance",
args().put("clientRequestId", "cancel-me").put("frames", 600))).path("operationId"));
value(call("studio_operation_cancel", args().put("operationId", receipt.path("operationId").asText())));
var result = value(completed("cancel-me"));
assertEquals("CANCELLED", result.path("result").path("status").asText(), result.toString());
assertTrue(result.path("progress").path("completedFrames").asInt() < 600);
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
assertEquals(session, value(call("studio_headless_state", args())).path("sessionId").asText());
assertArrayEquals(png(call("studio_operation_get", args().put("clientRequestId", "cancel-me"))), project.automation().snapshot().capture().png());
}
@Test void revokeWaitsForRuntimeAndDocumentRefreshAndRejectsLateCalls() throws Exception {
prepareLongRun();
value(call("studio_headless_advance", args().put("clientRequestId", "before-revoke").put("frames", 1)));
completed("before-revoke");
var lastCapture = project.automation().snapshot().capture();
var refreshEntered = new CompletableFuture<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("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "revoked")).path("structuredContent").path("error").path("code").asText());
assertSame(lastCapture, project.automation().snapshot().capture(), "Revoked work must not publish a late frame");
refreshGate.complete(null);
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
assertEquals(edited, refreshed.get()); assertEquals(edited, Files.readString(source));
assertStale(true);
} finally { refreshGate.complete(null); handoff.close(); }
}
@Test void waitingRevokeProjectCloseAndReopenNeverRestoreAuthority() throws Exception {
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
prepareLongRun(); startRunning("close-project");
fx(dev::unLoad);
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state(), "DEV does not own task lifetime");
project.close();
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
assertEquals("PROJECT_NOT_OPEN", call("studio_operation_get", args().put("clientRequestId", "close-project")).path("structuredContent").path("error").path("code").asText());
project = app.getBean(ProjectSessionFactory.class).open(project.projectReference());
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
assertEquals("INVALID_TASK", call("studio_build_start", args().put("clientRequestId", "late")).path("structuredContent").path("error").path("code").asText());
}
@Test void applicationContextShutdownClosesActiveProjectAndRuntime() throws Exception {
prepareLongRun(); startRunning("close-app");
app.close();
assertTrue(project.automation().snapshot().closed());
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
assertFalse(server.isRunning());
}
@Test void nonresponsiveOwnedHostIsKilledAndHumanCanRetryReclaim() throws Exception {
prepareLongRun(); startRunning("frozen");
var child = owned.stream().filter(p -> p.info().command().orElse("").endsWith("prometeu-headless")).findFirst().orElseThrow();
// POSIX desktop gate: freeze only this test's observed child, never a discovered user process.
assertEquals(0, new ProcessBuilder("/bin/kill", "-STOP", Long.toString(child.pid())).start().waitFor());
var outcome = project.automation().reclaim().toCompletableFuture().get(12, TimeUnit.SECONDS);
assertEquals(ControlResult.Status.CLEANUP_FAILED, outcome.status());
assertFalse(project.automation().snapshot().manualAllowed());
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
assertTrue(project.automation().reclaim().toCompletableFuture().get(5, TimeUnit.SECONDS).success());
assertTrue(project.automation().snapshot().manualAllowed());
}
@Test void realManualDebugStillRunsAfterAgentReleaseAndBlocksNewGrant() throws Exception {
// The existing manual protocol owns port 7777. Do not connect to someone else's Debug.
try (var probe = new java.net.ServerSocket()) { probe.bind(new java.net.InetSocketAddress("127.0.0.1", 7777)); }
acquire(); build("before-debug"); boot();
value(call("studio_control_release", args()));
try (var debug = app.getBean(p.studio.api.execution.ExecutionControllerFactory.class)
.create(project.projectReference(), project.projectLocalStudioSetup(), project.executionSession())) {
var running = debug.play().completion().toCompletableFuture().get(15, TimeUnit.SECONDS);
assertEquals(p.studio.api.execution.ExecutionState.RUNNING, running.state(), running.toString());
ProcessHandle.current().descendants().filter(p -> p.info().command().orElse("").startsWith(installation + "/")).forEach(owned::add);
assertEquals(ControlResult.Status.BUSY, project.automation().grant(false).toCompletableFuture().get(2, TimeUnit.SECONDS).status());
debug.stop();
assertEquals(p.studio.api.execution.ExecutionState.STOPPED, project.executionSession().snapshot().state());
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(7);
while ((!project.automation().snapshot().canGrant() || owned.stream().anyMatch(ProcessHandle::isAlive)) && System.nanoTime() < deadline) Thread.sleep(10);
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
assertTrue(project.automation().grant(false).toCompletableFuture().get(3, TimeUnit.SECONDS).success());
assertTrue(project.automation().reclaim().toCompletableFuture().get(3, TimeUnit.SECONDS).success());
}
@Test void forcedHostLossPreservesKnownProgressAndRequiresExplicitNewSession() throws Exception {
prepareLongRun(); startRunning("crash");
var child = owned.stream().filter(p -> p.info().command().orElse("").endsWith("prometeu-headless")).findFirst().orElseThrow();
assertTrue(child.destroyForcibly()); child.onExit().get(5, TimeUnit.SECONDS);
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
JsonNode result;
do { result = value(call("studio_operation_get", args().put("clientRequestId", "crash"))); if (result.path("workerTerminated").asBoolean()) break; Thread.sleep(5); }
while (System.nanoTime() < deadline);
assertTrue(result.path("workerTerminated").asBoolean());
assertEquals("INFRASTRUCTURE_FAILURE", result.path("failure").path("code").asText());
assertTrue(result.path("progress").path("completedFrames").asInt() < 600);
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
assertEquals(result.path("operationId"), value(call("studio_headless_advance", args().put("clientRequestId", "crash").put("frames", 600))).path("operationId"));
value(call("studio_headless_shutdown", args())); String previous = session; boot(); assertNotEquals(previous, session);
value(call("studio_headless_advance", args().put("clientRequestId", "after-crash").put("frames", 1)));
assertEquals("SUCCEEDED", value(completed("after-crash")).path("result").path("status").asText());
}
@Test void compileErrorAndGuestFaultCanBeCorrectedThroughHttpWithinTheSameTask() throws Exception {
acquire(); String identity = task; String original = Files.readString(source);
build("good"); boot();
Files.writeString(source, "fn frame( {");
var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString());
assertFalse(value(call("studio_language_query", query)).path("result").isEmpty());
value(call("studio_build_start", args().put("clientRequestId", "invalid")));
var failed = value(completed("invalid")).path("result");
assertEquals("FAILED", failed.path("status").asText()); assertFalse(failed.path("diagnostics").isEmpty());
assertEquals(identity, project.automation().snapshot().task().value());
Files.writeString(source, original.replace("x = x + 1;", "x = x / (x - x);"));
build("guest-fault"); boot();
value(call("studio_headless_advance", args().put("clientRequestId", "faulted").put("frames", 3)));
var fault = value(completed("faulted")).path("result");
assertEquals("GUEST_FAULT", fault.path("status").asText()); assertFalse(fault.path("diagnostics").isEmpty());
assertFalse(value(call("studio_headless_fault", args())).path("fault").isNull());
assertEquals(identity, project.automation().snapshot().task().value());
Files.writeString(source, original); assertTrue(value(call("studio_language_query", query)).path("result").isEmpty());
build("corrected"); boot();
value(call("studio_headless_advance", args().put("clientRequestId", "corrected-run").put("frames", 3)));
assertEquals("SUCCEEDED", value(completed("corrected-run")).path("result").path("status").asText());
assertEquals(identity, project.automation().snapshot().task().value());
value(call("studio_control_release", args())); assertTrue(project.automation().snapshot().manualAllowed());
}
@Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception {
assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100)));
var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000)));
assertTrue(sdk.toString().contains("InputPad"), "Consult installed SDK source through the indexed read-only reference");
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
task = value(call("studio_control_acquire", args())).path("taskId").asText();
assertFalse(task.isBlank());
// Agent-native edit of the installed example; SDK remains unchanged.
String edited = Files.readString(source).replace("import { Gfx } from @sdk:gfx;",
"import { Gfx } from @sdk:gfx;\nimport { Input } from @sdk:input;")
.replace("x = x + 1;", "if (Input.pad().right().down()) { x = x + 3; } else { x = x + 1; }");
Files.writeString(source, edited);
var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString());
assertTrue(value(call("studio_language_query", query)).path("result").isEmpty());
var symbols = args().put("operation", "documentSymbols"); symbols.putObject("parameters").put("uri", source.toUri().toString());
assertTrue(value(call("studio_language_query", symbols)).path("result").toString().contains("frame"));
int inputOffset = edited.indexOf("x = x + 3;") + "x = ".length();
String preceding = edited.substring(0, inputOffset);
var definition = args().put("operation", "definition");
definition.putObject("parameters").put("uri", source.toUri().toString()).putObject("position")
.put("line", preceding.chars().filter(c -> c == '\n').count())
.put("character", inputOffset - preceding.lastIndexOf('\n') - 1);
var locations = value(call("studio_language_query", definition)).path("result");
assertFalse(locations.isEmpty(), "Navigate the saved PBS source through the actual LSP");
assertEquals(source.toUri().toString(), locations.get(0).path("uri").asText());
build("first-build"); boot();
assertEquals("NO_FRAME_AVAILABLE", call("studio_headless_capture", args()).path("structuredContent").path("error").path("code").asText());
List<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", server.connection().authorizationHeader()).header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
if (connection != null) request.header("Mcp-Session-Id", connection);
return client.send(request.POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(), HttpResponse.BodyHandlers.ofString());
}
JsonNode value(JsonNode result) { assertFalse(result.path("isError").asBoolean(), result.toString()); return result.path("structuredContent").path("value"); }
byte[] png(JsonNode result) {
if (result.has("data")) return Base64.getDecoder().decode(result.path("data").asText());
assertEquals("image", result.path("content").get(1).path("type").asText());
assertEquals("image/png", result.path("content").get(1).path("mimeType").asText());
return Base64.getDecoder().decode(result.path("content").get(1).path("data").asText());
}
}
@@ -0,0 +1,97 @@
package p.studio.app.runtime;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.automation.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class HeadlessProcessSessionTest {
@TempDir Path root;
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 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();
}
}
+5 -1
View File
@@ -14,7 +14,11 @@ dependencies {
testImplementation(project(":prometeu-infra"))
testImplementation(project(":prometeu-lsp:prometeu-lsp-api"))
testImplementation(project(":prometeu-lsp:prometeu-lsp-v1"))
testImplementation(project(":prometeu-studio"))
testImplementation(project(":prometeu-packer:prometeu-packer-api"))
testImplementation(project(":prometeu-packer:prometeu-packer-v1"))
testImplementation(project(":prometeu-studio-api"))
testImplementation(project(":prometeu-studio-core"))
testImplementation(project(":prometeu-studio-ui-javafx"))
testImplementation(project(":prometeu-app"))
}
@@ -0,0 +1,97 @@
package p.studio.architecture;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
@AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class)
class StudioBoundaryArchTest {
@ArchTest
static final ArchRule automationTransportStaysInTheApp = noClasses()
.that().resideInAnyPackage("p.studio.api..", "p.studio.core..", "p.studio.ui..")
.should().dependOnClassesThat().resideInAnyPackage(
"p.studio.app.mcp..", "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
static final ArchRule staticContainerCannotReturn = noClasses()
.that().resideInAnyPackage("p.studio..")
.should().haveSimpleName("Container")
.because("DEC-0059 requires the static service locator to be physically absent");
@ArchTest
static final ArchRule appContainerCompatibilityBridgeCannotReturn = noClasses()
.that().resideInAnyPackage("p.studio..")
.should().haveSimpleName("AppContainer")
.because("DEC-0059 requires Spring composition without a legacy service bag");
@ArchTest
static final ArchRule studioApiIsFrameworkAndProviderNeutral = noClasses()
.that().resideInAPackage("p.studio.api..")
.should().dependOnClassesThat().resideInAnyPackage(
"javafx..",
"org.springframework..",
"org.springframework.modulith..",
"p.packer..",
"p.studio.compiler..",
"p.studio.lsp..",
"p.studio.utilities..",
"p.studio.core..",
"p.studio.ui..")
.because("DEC-0059 requires a toolkit and provider neutral public Studio API");
@ArchTest
static final ArchRule studioCoreDoesNotDependOnJavaFx = noClasses()
.that().resideInAPackage("p.studio.core..")
.should().dependOnClassesThat().resideInAPackage("javafx..")
.because("DEC-0059 requires the Studio Core to compile without JavaFX");
@ArchTest
static final ArchRule studioCoreDoesNotDependOnSpring = noClasses()
.that().resideInAPackage("p.studio.core..")
.should().dependOnClassesThat().resideInAPackage("org.springframework..")
.because("DEC-0059 confines Spring to application composition and keeps core as constructor-injected POJOs");
@ArchTest
static final ArchRule studioCoreDoesNotDependOnLegacySharedInfrastructure = noClasses()
.that().resideInAPackage("p.studio.core..")
.should().dependOnClassesThat().resideInAPackage("p.studio.utilities..")
.because("DEC-0059 requires the extracted core to own explicit contracts instead of inheriting the mixed Studio utility classpath");
@ArchTest
static final ArchRule javaFxAdapterDoesNotDependOnCoreOrProviderImplementations = noClasses()
.that().resideInAPackage("p.studio.ui.javafx..")
.should().dependOnClassesThat().resideInAnyPackage(
"p.studio.core..",
"p.packer..",
"p.studio.compiler..",
"p.studio.lsp..",
"p.studio.utilities..")
.because("DEC-0059 requires JavaFX to consume Studio API contracts only");
@ArchTest
static final ArchRule javaFxAdapterDoesNotOrchestrateTheFileSystem = noClasses()
.that().resideInAPackage("p.studio.ui.javafx..")
.should().dependOnClassesThat().haveFullyQualifiedName("java.nio.file.Files")
.because("DEC-0059 keeps filesystem orchestration behind neutral Studio services");
@ArchTest
static final ArchRule javaFxAdapterDoesNotOwnSerialization = noClasses()
.that().resideInAPackage("p.studio.ui.javafx..")
.should().dependOnClassesThat().resideInAPackage("com.fasterxml.jackson..")
.because("DEC-0059 keeps serialization in core or application adapters, not visual controls");
@ArchTest
static final ArchRule packerDoesNotDependOnStudio = noClasses()
.that().resideInAPackage("p.packer..")
.should().dependOnClassesThat().resideInAnyPackage(
"p.studio.api..",
"p.studio.core..",
"p.studio.ui..",
"p.studio.ui.javafx.window..",
"p.studio.ui.javafx.workspaces..")
.because("DEC-0059 keeps p.packer autonomous and dependency direction Studio to Packer");
}
@@ -1,3 +1,5 @@
import java.security.MessageDigest
plugins {
id("gradle.java-library-conventions")
}
@@ -8,3 +10,47 @@ dependencies {
implementation(project(":prometeu-compiler:prometeu-frontend-api"))
implementation(project(":prometeu-compiler:prometeu-compiler-core"))
}
// Build-time projection of owner-maintained sources; no second normative copy is edited by Studio.
val pbsSpecs = rootProject.layout.projectDirectory.dir("docs/specs/compiler-languages/pbs")
val pbsResources = layout.projectDirectory.dir("src/main/resources")
val generatePbsKnowledge by tasks.registering(Sync::class) {
from(pbsSpecs) { include("*.md"); into("pbs-knowledge/specs") }
into(layout.buildDirectory.dir("generated/pbsKnowledge"))
inputs.files(fileTree(pbsResources) { include("game/stdlib/**/*.pbs", "game/stdlib/**/*.barrel", "pbs-knowledge/examples/**") })
doLast {
val entries = mutableListOf<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()!!.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) }
@@ -13,11 +13,29 @@ import p.studio.compiler.pbs.semantics.PbsEditorialSignatureHelp;
import p.studio.compiler.pbs.semantics.PbsEditorialSymbolKind;
import p.studio.compiler.pbs.semantics.PbsEditorialSupportService;
import p.studio.compiler.pbs.semantics.PbsEditorialSupportService.EditorialDocument;
import p.studio.compiler.models.SourceKind;
import p.studio.compiler.pbs.semantics.PbsEditorialRename;
import p.studio.compiler.pbs.semantics.PbsEditorialWorkspaceSymbol;
import p.studio.compiler.pbs.PbsCallHierarchy;
import p.studio.compiler.pbs.PbsDocumentFormatter;
import p.studio.compiler.pbs.PbsSemanticTokenOverlay;
import p.studio.compiler.pbs.PbsStructureRanges;
import p.studio.compiler.pbs.semantics.PbsQuickFix;
import p.studio.compiler.pbs.semantics.PbsQuickFixCollector;
import p.studio.compiler.services.PBSFrontendPhaseService.PbsSemanticReadSurface;
import p.studio.compiler.services.FrontendCallHierarchyItem;
import p.studio.compiler.services.FrontendCallSite;
import p.studio.compiler.services.FrontendCodeAction;
import p.studio.compiler.services.FrontendCompletionCandidate;
import p.studio.compiler.services.FrontendSymbolKind;
import p.studio.compiler.services.FrontendDocumentLink;
import p.studio.compiler.services.FrontendFoldingRange;
import p.studio.compiler.services.FrontendSelectionRange;
import p.studio.compiler.services.FrontendDefinitionLocation;
import p.studio.compiler.services.FrontendDocumentRequest;
import p.studio.compiler.services.FrontendDocumentSymbol;
import p.studio.compiler.services.FrontendRenameEdit;
import p.studio.compiler.services.FrontendRenameResult;
import p.studio.compiler.services.FrontendDocumentation;
import p.studio.compiler.services.FrontendEditorialContext;
import p.studio.compiler.services.FrontendHover;
@@ -25,16 +43,20 @@ import p.studio.compiler.services.FrontendLanguageService;
import p.studio.compiler.services.FrontendSignature;
import p.studio.compiler.services.FrontendSignatureHelp;
import p.studio.compiler.services.FrontendSymbolKind;
import p.studio.compiler.services.FrontendWorkspaceRequest;
import p.studio.compiler.services.FrontendWorkspaceSymbol;
import p.studio.compiler.services.PBSFrontendPhaseService;
import p.studio.compiler.source.Span;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.source.tables.FileTableReader;
import p.studio.compiler.source.tables.ModuleReference;
import p.studio.utilities.structures.ReadOnlyList;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
@@ -55,6 +77,23 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
this.semanticTokenProvider = Objects.requireNonNull(semanticTokenProvider, "semanticTokenProvider");
}
@Override
public Optional<FrontendEditorialContext> prepareEditorialContext(final FrontendPhaseContext phaseContext) {
if (phaseContext == null) {
return Optional.empty();
}
final var semanticReadSurface = PBSFrontendPhaseService.semanticReadSurface(
phaseContext,
DiagnosticSink.empty(),
BuildingIssueSink.empty());
return Optional.of(new FrontendEditorialContext(
null,
ReadOnlyList.empty(),
phaseContext.feSurfaceContext(),
phaseContext.fileTable,
semanticReadSurface));
}
@Override
public Optional<FrontendEditorialContext> prepareEditorialContext(
final FrontendPhaseContext phaseContext,
@@ -100,6 +139,10 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
return List.of();
}
if (insideModuleRef(ast, offset)
&& editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface) {
return moduleCompletions(surface.moduleCompletionLabels());
}
@SuppressWarnings("unchecked")
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
@@ -281,15 +324,392 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
.toList();
}
@Override
public List<FrontendWorkspaceSymbol> workspaceSymbols(
final FrontendWorkspaceRequest request,
final FrontendEditorialContext editorialContext) {
if (request == null
|| editorialContext == null
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)
|| !(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|| surface.astByFile() == null
|| surface.astByFile().isEmpty()) {
return List.of();
}
final ArrayList<FrontendWorkspaceSymbol> symbols = new ArrayList<>();
for (final var entry : surface.astByFile().entrySet()) {
final Path path = pathForRegularSource(entry.getKey(), fileTable);
if (path == null) {
continue;
}
final PbsAst.File fileAst = entry.getValue();
if (fileAst == null) {
continue;
}
for (final PbsEditorialWorkspaceSymbol symbol : editorialSupportService.workspaceSymbols(
fileAst,
request.query())) {
toFrontendWorkspaceSymbol(symbol, path).ifPresent(symbols::add);
}
}
symbols.sort(Comparator
.comparing(FrontendWorkspaceSymbol::name, String.CASE_INSENSITIVE_ORDER)
.thenComparing(symbol -> symbol.path().toString())
.thenComparingInt(FrontendWorkspaceSymbol::startOffset));
return List.copyOf(symbols);
}
@Override
public Optional<FrontendDefinitionLocation> prepareRename(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final int offset) {
final PbsEditorialRename planned = editorialRename(request, editorialContext, offset, null);
if (planned == null || !planned.allowed()) {
return Optional.empty();
}
if (!(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
return Optional.empty();
}
if (physicalIdentity(planned, fileTable).isEmpty()) {
return Optional.empty();
}
return toFrontendLocation(planned.placeholder(), fileTable);
}
@Override
public FrontendRenameResult rename(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final int offset,
final String newName) {
if (newName == null) {
return FrontendRenameResult.refused("invalid identifier");
}
final PbsEditorialRename planned = editorialRename(request, editorialContext, offset, newName);
if (planned == null) {
return FrontendRenameResult.refused("not renameable");
}
if (!planned.allowed()) {
return FrontendRenameResult.refused(planned.refusal());
}
if (!(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
return FrontendRenameResult.refused("not renameable");
}
if (physicalIdentity(planned, fileTable).isEmpty()) {
return FrontendRenameResult.refused("not renameable");
}
final LinkedHashMap<String, FrontendRenameEdit> edits = new LinkedHashMap<>();
for (final PbsEditorialLocation site : planned.sites()) {
toFrontendLocation(site, fileTable).ifPresent(location ->
edits.putIfAbsent(
frontendLocationKey(location),
new FrontendRenameEdit(
location.path(),
location.startOffset(),
location.endOffset(),
newName)));
}
if (edits.isEmpty()) {
return FrontendRenameResult.refused("not renameable");
}
return FrontendRenameResult.applied(List.copyOf(edits.values()));
}
@Override
public boolean documentLinksSupported() {
return true;
}
@Override
public List<FrontendDocumentLink> documentLinks(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext) {
if (request == null
|| editorialContext == null
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|| !(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|| surface.physicalModuleFileByReference() == null
|| ast.imports() == null) {
return List.of();
}
final ArrayList<FrontendDocumentLink> links = new ArrayList<>();
for (final PbsAst.ImportDecl importDecl : ast.imports()) {
if (importDecl == null || importDecl.moduleRef() == null) {
continue;
}
final PbsAst.ModuleRef moduleRef = importDecl.moduleRef();
final Span span = moduleRef.span();
if (span == null || span.isNone() || moduleRef.project() == null || moduleRef.project().isBlank()) {
continue;
}
final Path target = surface.physicalModuleFileByReference().get(
new ModuleReference(moduleRef.project(), moduleRef.pathSegments()));
if (target == null) {
continue;
}
links.add(new FrontendDocumentLink(
target,
toOffset(span.getStart()),
toOffset(span.getEnd())));
}
return List.copyOf(links);
}
@Override
public boolean foldingRangesSupported() {
return true;
}
@Override
public List<FrontendFoldingRange> foldingRanges(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext) {
return PbsStructureRanges.foldingRanges(request == null || request.documentText() == null
? ""
: request.documentText());
}
@Override
public boolean selectionRangesSupported() {
return true;
}
@Override
public List<FrontendSelectionRange> selectionRanges(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final List<Integer> offsets) {
return PbsStructureRanges.selectionRanges(
request == null || request.documentText() == null ? "" : request.documentText(),
offsets);
}
@Override
public boolean callHierarchySupported() {
return true;
}
@Override
public List<FrontendCallHierarchyItem> prepareCallHierarchy(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final int offset) {
final PbsAst.File ast = callHierarchyAst(editorialContext);
if (ast == null) {
return List.of();
}
return PbsCallHierarchy.prepare(ast, offset).stream().map(this::toCallItem).toList();
}
@Override
public List<FrontendCallSite> incomingCalls(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final FrontendCallHierarchyItem target) {
return callSites(callHierarchyAst(editorialContext), target, true);
}
@Override
public List<FrontendCallSite> outgoingCalls(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final FrontendCallHierarchyItem target) {
return callSites(callHierarchyAst(editorialContext), target, false);
}
private List<FrontendCallSite> callSites(
final PbsAst.File ast,
final FrontendCallHierarchyItem target,
final boolean incoming) {
if (ast == null || target == null) {
return List.of();
}
final PbsCallHierarchy.Callable callable = new PbsCallHierarchy.Callable(
target.name(),
target.method(),
target.startOffset(),
target.endOffset());
final var calls = incoming
? PbsCallHierarchy.incomingCalls(ast, callable)
: PbsCallHierarchy.outgoingCalls(ast, callable);
return calls.stream()
.map(call -> new FrontendCallSite(
toCallItem(incoming ? call.caller() : call.callee()),
call.startOffset(),
call.endOffset()))
.toList();
}
private static PbsAst.File callHierarchyAst(final FrontendEditorialContext editorialContext) {
if (editorialContext == null || !(editorialContext.syntaxTree() instanceof PbsAst.File ast)) {
return null;
}
return ast;
}
private FrontendCallHierarchyItem toCallItem(final PbsCallHierarchy.Callable callable) {
return new FrontendCallHierarchyItem(
callable.name(),
callable.method(),
callable.startOffset(),
callable.endOffset());
}
@Override
public boolean formattingSupported() {
return true;
}
@Override
public Optional<String> formatDocument(final FrontendDocumentRequest request) {
return Optional.of(PbsDocumentFormatter.format(
request == null || request.documentText() == null ? "" : request.documentText()));
}
@Override
public boolean codeActionsSupported() {
return true;
}
@Override
public List<FrontendCodeAction> codeActions(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext) {
if (request == null
|| editorialContext == null
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
return List.of();
}
final FileId fileId = ast.span() == null ? null : ast.span().getFileId();
final Path path = pathForRegularSource(fileId, fileTable);
if (path == null || !path.equals(request.documentPath().toAbsolutePath().normalize())) {
return List.of();
}
final boolean interfaceModule = editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface
&& surface.sourceKindByFile() != null
&& surface.sourceKindByFile().get(fileId) == SourceKind.SDK_INTERFACE;
final ArrayList<FrontendCodeAction> actions = new ArrayList<>();
for (final PbsQuickFix repair : PbsQuickFixCollector.collect(ast, interfaceModule)) {
actions.add(new FrontendCodeAction(
repair.title(),
repair.diagnosticCode(),
path,
repair.startOffset(),
repair.endOffset(),
repair.newText()));
}
return List.copyOf(actions);
}
private PbsEditorialRename editorialRename(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final int offset,
final String newName) {
if (request == null
|| editorialContext == null
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
return null;
}
@SuppressWarnings("unchecked")
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
final EditorialDocument cursorDocument = new EditorialDocument(
request.documentText(),
ast,
typedSupplementalTopDecls,
feSurfaceContext);
return editorialSupportService.rename(
cursorDocument,
offset,
newName,
projectDocuments(request, editorialContext, cursorDocument, fileTable));
}
private List<FrontendDefinitionLocation> physicalIdentity(
final PbsEditorialRename planned,
final FileTableReader fileTable) {
final ArrayList<FrontendDefinitionLocation> locations = new ArrayList<>();
for (final PbsEditorialLocation location : planned.identity()) {
toFrontendLocation(location, fileTable).ifPresent(locations::add);
}
return List.copyOf(locations);
}
@Override
public List<FrontendSemanticToken> semanticTokens(final FrontendDocumentRequest request) {
return semanticTokens(request == null ? "" : request.documentText());
return semanticTokens(request, null);
}
@Override
public List<FrontendSemanticToken> semanticTokens(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext) {
final String text = request == null || request.documentText() == null ? "" : request.documentText();
final List<FrontendSemanticToken> baseline = semanticTokenProvider.tokenize(text);
if (editorialContext == null
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)) {
return baseline;
}
@SuppressWarnings("unchecked")
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
return PbsSemanticTokenOverlay.apply(
baseline,
text,
ast,
typedSupplementalTopDecls,
feSurfaceContext,
editorialSupportService);
}
public List<FrontendSemanticToken> semanticTokens(final String documentText) {
return semanticTokenProvider.tokenize(documentText == null ? "" : documentText);
}
private static boolean insideModuleRef(final PbsAst.File ast, final int offset) {
if (ast == null || ast.imports() == null || offset < 0) {
return false;
}
for (final PbsAst.ImportDecl importDecl : ast.imports()) {
if (importDecl == null || importDecl.moduleRef() == null || importDecl.moduleRef().span() == null) {
continue;
}
final long start = importDecl.moduleRef().span().getStart();
final long end = importDecl.moduleRef().span().getEnd();
if (end > start && start <= offset && offset <= end) {
return true;
}
}
return false;
}
private static List<FrontendCompletionCandidate> moduleCompletions(final List<String> labels) {
if (labels == null || labels.isEmpty()) {
return List.of();
}
final ArrayList<FrontendCompletionCandidate> candidates = new ArrayList<>();
for (final String label : labels) {
if (label == null || label.isBlank()) {
continue;
}
candidates.add(new FrontendCompletionCandidate(
label,
FrontendSymbolKind.MODULE,
"module",
"",
""));
}
return List.copyOf(candidates);
}
private FrontendCompletionCandidate toFrontendCompletionCandidate(final PbsEditorialCompletionCandidate candidate) {
return new FrontendCompletionCandidate(
candidate.label(),
@@ -328,6 +748,22 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
return FrontendSymbolKind.valueOf(kind.name());
}
private Optional<FrontendWorkspaceSymbol> toFrontendWorkspaceSymbol(
final PbsEditorialWorkspaceSymbol symbol,
final Path path) {
if (symbol == null || path == null || symbol.span() == null || symbol.span().isNone()) {
return Optional.empty();
}
return Optional.of(new FrontendWorkspaceSymbol(
symbol.name(),
toFrontendSymbolKind(symbol.kind()),
symbol.detail(),
symbol.containerName(),
path,
toOffset(symbol.span().getStart()),
toOffset(symbol.span().getEnd())));
}
private FrontendDocumentSymbol toFrontendDocumentSymbol(final PbsEditorialDocumentSymbol symbol) {
final int start = toOffset(symbol.span().getStart());
final int end = toOffset(symbol.span().getEnd());
@@ -376,6 +812,15 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
return List.copyOf(documents);
}
private Path pathForRegularSource(
final FileId fileId,
final FileTableReader fileTable) {
if (!isRegularSource(fileId, fileTable)) {
return null;
}
return fileTable.get(fileId).getCanonPath().toAbsolutePath().normalize();
}
private boolean isRegularSource(
final FileId fileId,
final FileTableReader fileTable) {

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