From 71fb80efc3189b23c3303eb9fde6bb35c602aa40 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Thu, 19 Nov 2026 17:32:03 +0000 Subject: [PATCH] feat(studio): ship JavaFX 2 Play and delegate integration tooling Launch the JavaFX 2 project shell on Java 25 with an interactive viewport, managed Play lifecycle and project mutation guards. Preserve headless/MCP and save compatibility, and qualify exact runtime executable bundles. Separate unit JaCoCo gates from opt-in integration suites and use the internal Pong fixture for the headless visual pilot. Move maintenance and native conformance tools into tooling; retain the VS Code extension and update current navigation links. Validation: tooling make verify passed, including 1064 Studio unit tests, JaCoCo thresholds and 22 headless integration tests. --- README.md | 79 +- build.gradle.kts | 7 +- buildSrc/build.gradle.kts | 8 + .../gradle.java-common-conventions.gradle.kts | 7 +- ...-0079-typed-common-ir-to-production-pbx.md | 4 +- ...al-runtime-catalog-port-and-conformance.md | 2 +- .../LSN-0081-pbs-typed-values-and-input.md | 2 +- ...-arrays-optional-and-contract-execution.md | 2 +- ...s-function-values-and-explicit-captures.md | 2 +- ...e-constants-and-source-math-conformance.md | 2 +- ...t-random-handles-and-source-conformance.md | 2 +- ...guest-hooks-and-preserved-continuations.md | 2 +- ...-buffers-and-process-proven-persistence.md | 2 +- ...ete-generic-contracts-from-source-to-vm.md | 2 +- ...table-lists-and-stable-snapshot-cursors.md | 2 +- ...ate-linked-nodes-and-atomic-publication.md | 2 +- ...eusable-identity-and-source-set-buckets.md | 2 +- ...-key-identity-and-captured-associations.md | 2 +- ...ations-need-explicit-failure-boundaries.md | 2 +- ...rivate-array-stacks-and-circular-queues.md | 4 +- ...ities-and-installed-authoring-contracts.md | 2 +- ...uction-binding-and-lowering-corrections.md | 2 +- docs/specs/README.md | 3 +- ...onstants and Runtime Math Specification.md | 2 +- .../pbs/4. Static Semantics Specification.md | 2 +- ...Backend Spec-to-Test Conformance Matrix.md | 4 +- ...Typed Registry and PBX v0 Specification.md | 2 +- ...hell and Workspace Layout Specification.md | 5 + .../13. JavaFX 2 Foundation Specification.md | 26 +- .../14. Integrated Play Specification.md | 149 ++ ...roject-Local Studio State Specification.md | 7 + ... and Adapter Architecture Specification.md | 10 + docs/specs/studio/README.md | 11 +- docs/vm-arch/README.md | 2 +- files/config/Jenkinsfile | 5 +- files/config/README.md | 33 +- gradle/libs.versions.toml | 4 +- prometeu-app/build.gradle.kts | 53 +- .../src/main/java/p/studio/app/App.java | 7 +- .../app/StudioApplicationConfiguration.java | 7 +- .../java/p/studio/app/StudioUiFactory.java | 13 + .../app/assets/AssetCapacityProfiles.java | 34 +- .../app/runtime/studio/LatestFramePool.java | 48 + .../studio/StudioRuntimeConnection.java | 205 ++ .../runtime/studio/StudioRuntimeGateway.java | 121 + .../studio/app/runtime/studio/StudioWire.java | 81 + .../resources/asset-capacity/catalog.json | 66 + ...f51740782c04b7f85a3ec346d742547275d60.json | 1675 +++++++++++++ .../evidence/studio-play-native-capacity.json | 1675 +++++++++++++ .../java/p/studio/app/DevDesktopTest.java | 1 + .../StudioApplicationConfigurationTest.java | 1 + .../p/studio/app/StudioPlayDesktopTest.java | 235 ++ .../app/animation/AnimationDesktopTest.java | 1 + .../AnimationInstalledRuntimeTest.java | 1 + .../animation/AnimationIntegrationTest.java | 1 + .../animation/AssetAuthoringDesktopTest.java | 1 + .../animation/AssetBatchIntegrationTest.java | 1 + .../app/assets/AssetCapacityProfilesTest.java | 93 + .../app/compiler/InstalledKnowledgeTest.java | 1 + .../compiler/TargetBuildIntegrationTest.java | 1 + .../app/evidence/EvidenceIntegrationTest.java | 1 + .../app/install/InstalledConnectorTest.java | 12 +- .../app/lsp/AutomationLspQueriesTest.java | 1 + .../app/lsp/LanguageFailureContractTest.java | 1 + .../p/studio/app/lsp/LspDiscoveryTest.java | 1 + .../p/studio/app/mcp/LocalMcpServerTest.java | 1 + .../app/mcp/McpConnectionGuideTest.java | 1 + .../p/studio/app/mcp/McpTaskToolsTest.java | 1 + .../mcp/ProjectConnectionPublisherTest.java | 1 + .../StructuredDiagnosticsIntegrationTest.java | 1 + .../app/mcp/stdio/StudioMcpStdioTest.java | 1 + .../AssetCapacityInstalledRuntimeTest.java | 1 + ...AssetManagedBuildInstalledRuntimeTest.java | 1 + .../app/runtime/GuestTestPilotTest.java | 1 + .../app/runtime/GuestTestsDesktopTest.java | 1 + .../GuestTestsInstalledRuntimeTest.java | 1 + .../runtime/HeadlessInstalledRuntimeTest.java | 1 + .../app/runtime/HeadlessMcpDesktopTest.java | 1 + .../runtime/HeadlessProcessSessionTest.java | 1 + .../runtime/HeadlessTaskIntegrationTest.java | 46 +- .../runtime/MemcardInstalledRuntimeTest.java | 1 + .../StudioPlayInstalledRuntimeTest.java | 82 + .../runtime/studio/LatestFramePoolTest.java | 23 + .../runtime/studio/StudioPlayProcessTest.java | 90 + .../app/runtime/studio/StudioWireTest.java | 60 + prometeu-architecture-tests/build.gradle.kts | 1 + .../architecture/StudioBoundaryArchTest.java | 6 +- .../backend/irvm/PbsClosuresTest.java | 1 + .../backend/irvm/PbsGenericContractsTest.java | 1 + .../backend/irvm/PbsGenericStructsTest.java | 1 + .../backend/irvm/PbsGuestLifecycleTest.java | 1 + .../backend/irvm/PbsIdentityHashingTest.java | 1 + .../compiler/backend/irvm/PbsLinkedTest.java | 1 + .../backend/irvm/PbsListCursorTest.java | 1 + .../backend/irvm/PbsMapKeyvalTest.java | 1 + .../compiler/backend/irvm/PbsMemcardTest.java | 1 + .../compiler/backend/irvm/PbsResultTest.java | 1 + .../backend/irvm/PbsRuntimeAlignmentTest.java | 1 + .../backend/irvm/PbsRuntimeMathTest.java | 1 + .../backend/irvm/PbsRuntimeRandomTest.java | 1 + .../compiler/backend/irvm/PbsSetTest.java | 1 + .../backend/irvm/PbsSpriteAnimationTest.java | 1 + .../backend/irvm/PbsStackQueueTest.java | 1 + .../backend/irvm/PbsStructuredValuesTest.java | 1 + .../BackendGateIIntegrationTest.java | 1 + .../MainProjectPipelineIntegrationTest.java | 1 + .../integration/PbsFacadeDiagnosticTest.java | 1 + ...RuntimeBackedCompatibilityAdapterTest.java | 1 + .../SyntheticFrontendPipelineTest.java | 1 + .../ExternalSourceDevelopmentHostTest.java | 1 + .../lsp/services/LspServerLifecycleTest.java | 1 + .../services/PackerAssetContractTest.java | 1 + .../api/automation/ExecutionAuthority.java | 12 + .../studio/api/automation/ProjectAccess.java | 3 + .../api/execution/ExecutionController.java | 10 + .../execution/ExecutionControllerFactory.java | 5 + .../studio/api/execution/ExecutionFrame.java | 30 + .../studio/api/execution/ExecutionInput.java | 9 + .../api/execution/ExecutionSession.java | 5 + .../studio/api/execution/ExecutionState.java | 4 + .../p/studio/api/execution/PlayOptions.java | 6 + .../api/session/ProjectSessionFactory.java | 2 + .../DefaultExecutionControllerFactory.java | 6 + .../execution/DefaultExecutionSession.java | 21 +- .../InteractiveExecutionController.java | 174 ++ .../PlayStopExecutionController.java | 3 +- .../core/project/ProjectAccessRegistry.java | 23 + .../core/runtime/RuntimeConnection.java | 10 + .../p/studio/core/runtime/RuntimeGateway.java | 7 + .../runtime/RuntimeStopRefusedException.java | 6 + .../session/DefaultAutomationSession.java | 37 +- .../session/DefaultProjectSessionFactory.java | 14 +- .../InteractiveExecutionControllerTest.java | 103 + .../session/DefaultAutomationSessionTest.java | 17 + prometeu-studio-ui-javafx-2/README.md | 13 +- prometeu-studio-ui-javafx-2/build.gradle.kts | 2 + .../ui/javafx2/demo/ComponentGallery.java | 2 +- .../ui/javafx2/play/PlaybackViewport.java | 78 + .../studio/ui/javafx2/shell/MinimalShell.java | 9 +- .../window/StudioWindowCoordinator2.java | 226 ++ .../ui/javafx2/window/WindowResources.java | 29 + .../ui/javafx2/i18n/messages_en.properties | 26 + .../ui/javafx2/i18n/messages_pt_BR.properties | 26 + .../ui/javafx2/FoundationDesktopTest.java | 1 + .../studio/ui/javafx/utilities/i18n/I18n.java | 4 + .../workspaces/debug/DebugWorkspace.java | 4 + .../main/resources/i18n/messages.properties | 4 + .../resources/i18n/messages_pt_BR.properties | 4 + .../main/assets/.prometeu/cache.json | 20 +- tools/documentation/verify.py | 103 - .../PbsProductionCorpusProbe.java | 138 -- tools/pbs-production-corpus/README.md | 44 - .../qualify-installed-contracts.py | 74 - tools/pbs-production-corpus/run.py | 223 -- tools/pbx-conformance/README.md | 545 ----- tools/pbx-conformance/animation.rs | 118 - tools/pbx-conformance/lifecycle.rs | 219 -- tools/pbx-conformance/main.rs | 2085 ----------------- tools/pbx-conformance/memcard.rs | 533 ----- tools/pbx-conformance/result.rs | 56 - tools/pbx-conformance/run.py | 80 - tools/pbx-conformance/stack_queue.rs | 570 ----- tools/runtime-catalog/verify.py | 44 - 163 files changed, 5929 insertions(+), 4950 deletions(-) create mode 100644 docs/specs/studio/14. Integrated Play Specification.md create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/studio/LatestFramePool.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/studio/StudioRuntimeConnection.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/studio/StudioRuntimeGateway.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/studio/StudioWire.java create mode 100644 prometeu-app/src/main/resources/asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json create mode 100644 prometeu-app/src/main/resources/asset-capacity/evidence/studio-play-native-capacity.json create mode 100644 prometeu-app/src/test/java/p/studio/app/StudioPlayDesktopTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/assets/AssetCapacityProfilesTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/StudioPlayInstalledRuntimeTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/studio/LatestFramePoolTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/studio/StudioPlayProcessTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/studio/StudioWireTest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/automation/ExecutionAuthority.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionFrame.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionInput.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/execution/PlayOptions.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/execution/InteractiveExecutionController.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeStopRefusedException.java create mode 100644 prometeu-studio-core/src/test/java/p/studio/core/execution/InteractiveExecutionControllerTest.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/play/PlaybackViewport.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/StudioWindowCoordinator2.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/WindowResources.java delete mode 100644 tools/documentation/verify.py delete mode 100644 tools/pbs-production-corpus/PbsProductionCorpusProbe.java delete mode 100644 tools/pbs-production-corpus/README.md delete mode 100644 tools/pbs-production-corpus/qualify-installed-contracts.py delete mode 100644 tools/pbs-production-corpus/run.py delete mode 100644 tools/pbx-conformance/README.md delete mode 100644 tools/pbx-conformance/animation.rs delete mode 100644 tools/pbx-conformance/lifecycle.rs delete mode 100644 tools/pbx-conformance/main.rs delete mode 100644 tools/pbx-conformance/memcard.rs delete mode 100644 tools/pbx-conformance/result.rs delete mode 100644 tools/pbx-conformance/run.py delete mode 100644 tools/pbx-conformance/stack_queue.rs delete mode 100644 tools/runtime-catalog/verify.py diff --git a/README.md b/README.md index b1935797..b4cfafff 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ The root project is a monorepo with these main areas: - `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-studio-ui-javafx-2`: the default human-facing frontend and presentation foundation. +- `prometeu-studio-ui-javafx`: retained previous adapter and compatibility qualification surfaces. - `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. @@ -25,17 +26,30 @@ the enclosing [Prometeu Engineering workspace](../README.md) using ## Current Product Shape -The Studio shell currently organizes the product around four workspaces: +The normal and installed application opens the new project chooser. Open an existing +project, choose a qualified runtime installation, then use Play, Pause, Resume and +Stop. Close the project before opening another. A save-capable game requires an +existing development save image or an explicitly disposable session. -- Assets -- Debug -- DEV (external-agent authorization and observation) -- Shipper +Play prepares compiler/assets into the cartridge directory and starts an owned +native runtime process whose frames appear inside Studio. Zoom is x1/x2/x4 in +logical pixels with scrolling. Minimizing or switching applications pauses; +returning requires manual Resume. Closing stops the game, subject to save protection. +Play does not create a PMC or a distributable build. -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. +This first frontend slice does not mount editors, Assets/DEV/Shipper workspaces, +AI prompts/configuration or breakpoint debugging. Their existing service contracts, +headless runtime and MCP adapters remain separately tested. The previous DEV guide +below describes retained adapter behavior, not controls available in the new UI. +See the [integrated Play contract](docs/specs/studio/14.%20Integrated%20Play%20Specification.md). ## External Coding Agents (MCP) +The following authorization workflow belongs to the previous DEV adapter. The new +Play UI does not yet expose a grant/configuration surface. This omission does not +change the deterministic headless protocol, task authority, MCP tool schemas or +installed stdio connector; their process and adapter qualification gates remain. + Studio includes its own `mcp --project ` mode. Configure the native client once; project grants and desktop restarts no longer require copying ports or tokens. The initial integration targets Codex on macOS. @@ -219,7 +233,7 @@ follow-ups are consolidated in [LSN-0076](discussion/lessons/DSC-0068-studio-hea ## Requirements -- JDK 21 or newer recommended for local development +- JDK 25 for local compilation/tests and the bundled product runtime (Gradle 9.3.1) - Gradle wrapper (`./gradlew`) included in the repository - A desktop environment capable of running JavaFX @@ -237,12 +251,61 @@ Run the desktop application: ./gradlew :prometeu-app:run ``` +The new UI is the default. `:prometeu-studio-ui-javafx-2:run` and `:gallery` remain +separate foundation demonstrations, without a backend or a project. + +Opt-in integrated Play qualification (desktop/installed native runtime required): + +```sh +./gradlew :prometeu-app:studioPlayProcessTest -PstudioRuntimeInstall=/absolute/runtime-install +./gradlew :prometeu-app:studioPlayDesktopTest -PstudioRuntimeInstall=/absolute/runtime-install +``` + +Add `-PstudioPlayStress=true` for the 30-second presentation/FX-delay/20-cycle gate. +The headless visual evidence pilot uses a disposable copy of `test-projects/pong`. +Integration fixtures belong to this repository; no external port checkout is +required. A runtime's three executable identities must match a distributed +capacity profile; rebuilding a native binary does not automatically requalify it. + +Build the native umbrella distribution with `../runtime/scripts/local-dist.sh`. +It packages `prometeu`, `prometeu-runtime` (desktop/Studio Play) and +`prometeu-headless` (deterministic automation). Select the extracted +`../runtime/dist-staging/stable/prometeu-cli-` directory in Studio. +An unchanged dispatcher can belong to several releases: Studio selects a profile +only when all three executable hashes match the same qualified bundle. + +After changing a native binary, qualify the actual installation before building +or launching Studio with its updated catalog: + +```sh +make -C ../tooling venv +../tooling/.venv/bin/python ../tooling/scripts/qualify.py \ + --studio . \ + --runtime ../runtime/dist-staging/stable/prometeu-cli-aarch64-apple-darwin +``` + +This command executes the native glyph/scene 16/17 boundary test afresh, verifies +the evidence and executable identities, then publishes an exact capacity profile +under `prometeu-app/src/main/resources/asset-capacity`. Review/include those +resources when distributing Studio. It neither builds a replacement runtime nor +relaxes the execution guard. A failed qualification publishes no catalog entry. +The native build stays independent of the JVM; qualification is an explicit +consumer verification step, separate from pressing Play. + Run the test suite: ```bash ./gradlew test ``` +`test` runs unit tests and excludes JUnit `@Tag("integration")`. Integration +includes process/network/desktop qualification and real application or provider +composition, including fixture subprocesses. Existing integration suites remain +in this repository; `../tooling` prepares their environment and orchestrates +selected integration commands and builds. They are currently excluded from the +runtime and Studio pipelines; the opt-in commands above are separate checks. +Consolidated JaCoCo uses only the unit `test.exec` files. + Generate the aggregated coverage report: ```bash diff --git a/build.gradle.kts b/build.gradle.kts index 1984650c..e99ce379 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -12,18 +12,19 @@ dependencies { val jacocoTestReport = tasks.register("jacocoTestReport") { group = "Verification" - description = "Generates a consolidated JaCoCo report for all subprojects." + description = "Generates consolidated unit-test coverage for all subprojects." val javaSubprojects = subprojects.filter { subproject -> subproject.subprojects.isEmpty() && subproject.plugins.hasPlugin("java") } - dependsOn(javaSubprojects.map { it.tasks.withType() }) + dependsOn(javaSubprojects.map { it.tasks.named("jacocoTestReport") }) additionalSourceDirs.setFrom(javaSubprojects.map { it.layout.projectDirectory.dir("src/main/java") }) sourceDirectories.setFrom(javaSubprojects.map { it.layout.projectDirectory.dir("src/main/java") }) classDirectories.setFrom(javaSubprojects.map { it.layout.buildDirectory.dir("classes/java/main") }) - executionData.setFrom(fileTree(projectDir).include("**/build/jacoco/*.exec")) + // Opt-in integration tasks must not contribute coverage to the unit gate. + executionData.setFrom(javaSubprojects.map { it.layout.buildDirectory.file("jacoco/test.exec") }) reports { xml.required.set(true) diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index e4a377cb..2016b586 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -2,6 +2,14 @@ plugins { `kotlin-dsl` } +// Build logic can target Java 21 while the Studio product uses the Java 25 toolchain. +// Gradle's embedded Kotlin compiler does not yet emit JVM 25 bytecode. +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} +kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21) } } + repositories { gradlePluginPortal() mavenCentral() diff --git a/buildSrc/src/main/kotlin/gradle.java-common-conventions.gradle.kts b/buildSrc/src/main/kotlin/gradle.java-common-conventions.gradle.kts index e481000a..2be2a28f 100644 --- a/buildSrc/src/main/kotlin/gradle.java-common-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/gradle.java-common-conventions.gradle.kts @@ -29,12 +29,15 @@ dependencies { java { toolchain { - languageVersion = JavaLanguageVersion.of(21) + languageVersion = JavaLanguageVersion.of(25) } } +jacoco { toolVersion = libs.findVersion("jacoco").get().requiredVersion } + tasks.named("test") { - useJUnitPlatform() + description = "Runs unit tests only; integration verification belongs to prometeu-tooling." + useJUnitPlatform { excludeTags("integration") } finalizedBy("jacocoTestReport") } diff --git a/discussion/lessons/DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md b/discussion/lessons/DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md index 67095006..6b4cec6a 100644 --- a/discussion/lessons/DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md +++ b/discussion/lessons/DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md @@ -116,7 +116,7 @@ for runtime evidence. The intrinsic/native catalogue goldens are serialization fixtures and do not claim current PBS catalogue compatibility. Reproduce with the commands in -[the harness README](../../../tools/pbx-conformance/README.md). The harness +[the harness README](../../../../tooling/scripts/pbx-conformance/README.md). The harness creates its Cargo build outside the runtime checkout and saves generated PBX and observed JSON under the build-pipeline build directory. @@ -140,6 +140,6 @@ slot-to-type inference to conceal an incomplete handoff. - [Typed common Registry/PBX specification](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md) - [Backend conformance matrix](../../../docs/specs/compiler/22.%20Backend%20Spec-to-Test%20Conformance%20Matrix.md) -- [Runtime qualification harness](../../../tools/pbx-conformance/README.md) +- [Runtime qualification harness](../../../../tooling/scripts/pbx-conformance/README.md) - Runtime sources: registry_v0.rs, program_image.rs, registry_verifier, and devtools/headless-protocol/response.schema.json at the revision above. diff --git a/discussion/lessons/DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md b/discussion/lessons/DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md index 89ad31e3..923f9bbf 100644 --- a/discussion/lessons/DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md +++ b/discussion/lessons/DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md @@ -172,7 +172,7 @@ and behavior together. Roll back that set together if necessary. - [Normative catalog support](../../../docs/specs/compiler/24.%20Runtime%20Catalog%20Support%20Specification.md) - [Typed common Registry/PBX contract](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md) - [VM mirror and provider verification policy](../../../docs/vm-arch/README.md) -- [Production runtime harness](../../../tools/pbx-conformance/README.md) +- [Production runtime harness](../../../../tooling/scripts/pbx-conformance/README.md) - Runtime sources at the recorded revision: catalog.rs, builtins.rs, input_intrinsics.rs, math_intrinsics.rs, random_intrinsics.rs, random.rs, registry_verifier/{heights,types}.rs and tests/numeric_contract.rs. diff --git a/discussion/lessons/DSC-0076-pbs-existing-types-input-alignment/LSN-0081-pbs-typed-values-and-input.md b/discussion/lessons/DSC-0076-pbs-existing-types-input-alignment/LSN-0081-pbs-typed-values-and-input.md index 8698dbc4..37af79f0 100644 --- a/discussion/lessons/DSC-0076-pbs-existing-types-input-alignment/LSN-0081-pbs-typed-values-and-input.md +++ b/discussion/lessons/DSC-0076-pbs-existing-types-input-alignment/LSN-0081-pbs-typed-values-and-input.md @@ -80,4 +80,4 @@ Frontend negatives cover invalid Button arguments, mixed int/long variables, lit - [Shared runtime catalog contract](../../../docs/specs/compiler/24.%20Runtime%20Catalog%20Support%20Specification.md) - [Typed registry and PBX contract](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md) - [PBS source-to-PBX qualification](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java) -- [Actual-runtime harness instructions](../../../tools/pbx-conformance/README.md) +- [Actual-runtime harness instructions](../../../../tooling/scripts/pbx-conformance/README.md) diff --git a/discussion/lessons/DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md b/discussion/lessons/DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md index fd6d3822..4d2e09f9 100644 --- a/discussion/lessons/DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md +++ b/discussion/lessons/DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md @@ -64,7 +64,7 @@ The installed knowledge package includes the specification and an executable [ar ## Implementation references - [Source conformance tests](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java) -- [Runtime harness and reproduction instructions](../../../tools/pbx-conformance/README.md) +- [Runtime harness and reproduction instructions](../../../../tooling/scripts/pbx-conformance/README.md) - [Static semantics](../../../docs/specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md) - [Dynamic semantics](../../../docs/specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md) - [Earlier typed common IR/PBX lesson](../DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md) diff --git a/discussion/lessons/DSC-0080-pbs-closures-and-indirect-calls/LSN-0084-pbs-function-values-and-explicit-captures.md b/discussion/lessons/DSC-0080-pbs-closures-and-indirect-calls/LSN-0084-pbs-function-values-and-explicit-captures.md index ecc4ac55..cfc55dc4 100644 --- a/discussion/lessons/DSC-0080-pbs-closures-and-indirect-calls/LSN-0084-pbs-function-values-and-explicit-captures.md +++ b/discussion/lessons/DSC-0080-pbs-closures-and-indirect-calls/LSN-0084-pbs-function-values-and-explicit-captures.md @@ -109,5 +109,5 @@ Common mistakes to avoid: - [Normative function and capture specification](../../../docs/specs/compiler-languages/pbs/15.%20First-Class%20Functions%20and%20Captures%20Specification.md). - [Implementation evidence and reproducible commands](../../evidence/DSC-0080-implementation/README.md). -- [Production VM conformance harness](../../../tools/pbx-conformance/README.md). +- [Production VM conformance harness](../../../../tooling/scripts/pbx-conformance/README.md). - [Executable installed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/closures.pbs). diff --git a/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md b/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md index 14b00cf7..1d62666a 100644 --- a/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md +++ b/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md @@ -152,7 +152,7 @@ explicitly reported by the full harness; original payloads are preserved. - [Service constants and runtime math specification](../../../docs/specs/compiler-languages/pbs/19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md) - [Runtime catalog policy](../../../docs/specs/compiler/24.%20Runtime%20Catalog%20Support%20Specification.md) -- [Production harness](../../../tools/pbx-conformance/README.md) +- [Production harness](../../../../tooling/scripts/pbx-conformance/README.md) - [Catalog-port lesson](../DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md) - Historical execution artifacts: DEC-0069 and PLN-0148, removed by CLI housekeeping after completion. diff --git a/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md b/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md index 7bec226d..328f3c61 100644 --- a/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md +++ b/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md @@ -154,7 +154,7 @@ SDK/spec/example delivery, not execution through an installed runtime process. - [PBS Random specification](../../../docs/specs/compiler-languages/pbs/20.%20Runtime%20Random%20Integration%20Specification.md). - [Typed arrays and optional execution](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md). - [Functions and captures](../../../docs/specs/compiler-languages/pbs/15.%20First-Class%20Functions%20and%20Captures%20Specification.md). -- [Conformance commands and boundaries](../../../tools/pbx-conformance/README.md). +- [Conformance commands and boundaries](../../../../tooling/scripts/pbx-conformance/README.md). - [Provider Random specification](../../../../runtime/docs/specs/runtime/02e-vm-owned-random-core.md). - [Provider qualification](../../../../runtime/docs/vm-arch/RANDOM_QUALIFICATION.md). - Historical accepted DEC-0070 and completed PLN-0149: obligations are preserved diff --git a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md index 28db2a21..c0de7085 100644 --- a/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md +++ b/discussion/lessons/DSC-0084-pbs-guest-lifecycle-hooks/LSN-0097-explicit-guest-hooks-and-preserved-continuations.md @@ -155,6 +155,6 @@ remains DSC-0085. Other platforms are not claimed by this evidence. - [PBS lowering](<../../../docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md>). - [Common typed Registry/PBX](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md). - [Source-to-PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java). -- [Production VM/foreground harness](../../../tools/pbx-conformance/lifecycle.rs). +- [Production VM/foreground harness](../../../../tooling/scripts/pbx-conformance/lifecycle.rs). - [Installed lifecycle guide](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md). - Runtime [role binding](../../../../runtime/docs/specs/runtime/02c-program-registry-and-pbx-v0.md) and [controlled execution](../../../../runtime/docs/specs/runtime/09a-coroutines-and-cooperative-scheduling.md). diff --git a/discussion/lessons/DSC-0085-studio-memcard-persistence-integration/LSN-0099-explicit-buffers-and-process-proven-persistence.md b/discussion/lessons/DSC-0085-studio-memcard-persistence-integration/LSN-0099-explicit-buffers-and-process-proven-persistence.md index f358e5ae..1bbdc3b9 100644 --- a/discussion/lessons/DSC-0085-studio-memcard-persistence-integration/LSN-0099-explicit-buffers-and-process-proven-persistence.md +++ b/discussion/lessons/DSC-0085-studio-memcard-persistence-integration/LSN-0099-explicit-buffers-and-process-proven-persistence.md @@ -192,5 +192,5 @@ Build/Play/UI/MCP deployment remain outside this capacity and belong to DSC-0086 - [Project-local state and media selection](<../../../docs/specs/studio/8. Project-Local Studio State Specification.md>). - [DEV and automation](<../../../docs/specs/studio/10. DEV and Automation Specification.md>). - [MCP tool contract](<../../../docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md>). -- [Producer/native/process runner](../../../tools/pbx-conformance/README.md). +- [Producer/native/process runner](../../../../tooling/scripts/pbx-conformance/README.md). - [Independent runtime provider lesson](../../../../runtime/discussion/lessons/DSC-0068-memcard-public-host-persistence/LSN-0073-public-persistence-is-a-process-and-ownership-contract.md). diff --git a/discussion/lessons/DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md b/discussion/lessons/DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md index 78433aa7..bf812e22 100644 --- a/discussion/lessons/DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md +++ b/discussion/lessons/DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md @@ -185,7 +185,7 @@ legacy integration cases; production fixtures exercise the required paths. Additional focused cases cover mutual recursion and imported alias navigation. Workflow validation and whitespace checks passed before completion. -Reproduce with the gates in the [conformance harness documentation](../../../tools/pbx-conformance/README.md). +Reproduce with the gates in the [conformance harness documentation](../../../../tooling/scripts/pbx-conformance/README.md). The new specification and `contracts.pbs` example are discoverable in installed knowledge, not only in the source checkout. diff --git a/discussion/lessons/DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md b/discussion/lessons/DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md index 5671cb64..122a7398 100644 --- a/discussion/lessons/DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md +++ b/discussion/lessons/DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md @@ -248,7 +248,7 @@ production corpus, full regressions and pinned provenance. and [ordinary typed storage](../../../../runtime/crates/console/prometeu-vm/src/virtual_machine/collections.rs). - [Source fixture generator](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java), [neutral IR fixtures](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java) - and [production harness instructions](../../../tools/pbx-conformance/README.md). + and [production harness instructions](../../../../tooling/scripts/pbx-conformance/README.md). - [Mutation-phase migration](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md), [generic structs lesson](../DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md) and [generic contracts lesson](../DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md). diff --git a/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md b/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md index 8d53177e..e8284b1c 100644 --- a/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md +++ b/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md @@ -231,7 +231,7 @@ NonFiniteValue, remain explicitly reported with original payloads. - [SDK source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs), [source corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java), [neutral producer](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java) - and [production harness instructions](../../../tools/pbx-conformance/README.md). + and [production harness instructions](../../../../tooling/scripts/pbx-conformance/README.md). - [Current provider typed storage](../../../../runtime/crates/console/prometeu-vm/src/virtual_machine/collections.rs), [sequential mutation migration](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md) and [List/Cursor lesson](../DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md). diff --git a/discussion/lessons/DSC-0092-pbs-sdk-set/LSN-0093-reusable-identity-and-source-set-buckets.md b/discussion/lessons/DSC-0092-pbs-sdk-set/LSN-0093-reusable-identity-and-source-set-buckets.md index 0e9a311b..8d6a409d 100644 --- a/discussion/lessons/DSC-0092-pbs-sdk-set/LSN-0093-reusable-identity-and-source-set-buckets.md +++ b/discussion/lessons/DSC-0092-pbs-sdk-set/LSN-0093-reusable-identity-and-source-set-buckets.md @@ -214,5 +214,5 @@ JUnit cases are listed separately from the mandatory runtime corpus. - [Common Registry/PBX specification](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md). - [SDK collection source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs). - [Set source fixtures](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java). -- [Conformance tooling and reproduction](../../../tools/pbx-conformance/README.md). +- [Conformance tooling and reproduction](../../../../tooling/scripts/pbx-conformance/README.md). - [Sequential mutation predecessor](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md). diff --git a/discussion/lessons/DSC-0093-pbs-sdk-map-keyval/LSN-0094-map-presence-key-identity-and-captured-associations.md b/discussion/lessons/DSC-0093-pbs-sdk-map-keyval/LSN-0094-map-presence-key-identity-and-captured-associations.md index e802e07a..ab617e33 100644 --- a/discussion/lessons/DSC-0093-pbs-sdk-map-keyval/LSN-0094-map-presence-key-identity-and-captured-associations.md +++ b/discussion/lessons/DSC-0093-pbs-sdk-map-keyval/LSN-0094-map-presence-key-identity-and-captured-associations.md @@ -189,6 +189,6 @@ evidence and are not counted as new Map conformance. - [Executable installed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/maps.pbs). - [SDK algorithms](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs). - [Source-to-PBX qualification](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMapKeyvalTest.java). -- [Harness reproduction](../../../tools/pbx-conformance/README.md). +- [Harness reproduction](../../../../tooling/scripts/pbx-conformance/README.md). - [Set/Identity predecessor](../DSC-0092-pbs-sdk-set/LSN-0093-reusable-identity-and-source-set-buckets.md). - [Sequential mutation boundaries](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md). diff --git a/discussion/lessons/DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md b/discussion/lessons/DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md index fd165913..d6b7583e 100644 --- a/discussion/lessons/DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md +++ b/discussion/lessons/DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md @@ -204,7 +204,7 @@ they are not silently relabeled as schema conformance or fixed in runtime here. - [List/Cursor](../../../docs/specs/compiler-languages/pbs/21.%20SDK%20List%20and%20Cursor%20Specification.md), [Linked](../../../docs/specs/compiler-languages/pbs/22.%20SDK%20Linked%20and%20Cursor%20Specification.md) and [Array/optional](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md). -- [Conformance commands and coverage](../../../tools/pbx-conformance/README.md). +- [Conformance commands and coverage](../../../../tooling/scripts/pbx-conformance/README.md). - [Selected provider pin](../../../docs/vm-arch/runtime-catalog.properties). - Original decisions/planning: accepted DEC-0077 and completed PLN-0155 in DSC-0096, consolidated here before their required housekeeping removal. diff --git a/discussion/lessons/DSC-0097-pbs-sdk-stack-queue/LSN-0095-private-array-stacks-and-circular-queues.md b/discussion/lessons/DSC-0097-pbs-sdk-stack-queue/LSN-0095-private-array-stacks-and-circular-queues.md index 500cfc86..91e2a529 100644 --- a/discussion/lessons/DSC-0097-pbs-sdk-stack-queue/LSN-0095-private-array-stacks-and-circular-queues.md +++ b/discussion/lessons/DSC-0097-pbs-sdk-stack-queue/LSN-0095-private-array-stacks-and-circular-queues.md @@ -187,7 +187,7 @@ Avoid these maintenance mistakes: [shared Cursor](../../../docs/specs/compiler-languages/pbs/21.%20SDK%20List%20and%20Cursor%20Specification.md). - [SDK algorithms](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs). - [Source/PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java). -- [Conformance module](../../../tools/pbx-conformance/stack_queue.rs) and - [reproduction instructions](../../../tools/pbx-conformance/README.md). +- [Conformance module](../../../../tooling/scripts/pbx-conformance/stack_queue.rs) and + [reproduction instructions](../../../../tooling/scripts/pbx-conformance/README.md). - [Sequential mutation lessons](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md). - [Evidence and R1–R9 coverage](evidence/README.md). diff --git a/discussion/lessons/DSC-0108-pbs-production-contracts-executable-examples/LSN-0107-quoted-project-identities-and-installed-authoring-contracts.md b/discussion/lessons/DSC-0108-pbs-production-contracts-executable-examples/LSN-0107-quoted-project-identities-and-installed-authoring-contracts.md index 06a35d5d..f8a4bcba 100644 --- a/discussion/lessons/DSC-0108-pbs-production-contracts-executable-examples/LSN-0107-quoted-project-identities-and-installed-authoring-contracts.md +++ b/discussion/lessons/DSC-0108-pbs-production-contracts-executable-examples/LSN-0107-quoted-project-identities-and-installed-authoring-contracts.md @@ -153,7 +153,7 @@ Normative source: PBS [3 — Core Syntax](../../../docs/specs/compiler-languages [14 — Typed Arrays/Optional](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md) and [Compiler 14 — Resolution/Linking](../../../docs/specs/compiler/14.%20Name%20Resolution%20and%20Module%20Linking%20Specification.md). -Reproduction: [production corpus runner guide](../../../tools/pbs-production-corpus/README.md), +Reproduction: [production corpus runner guide](../../../../tooling/scripts/pbs-production-corpus/README.md), [installed expectations](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/production/cases.json), [installed probe](../../../prometeu-app/src/test/java/p/studio/app/compiler/ProductionContractsInstalledProbe.java) and [quoted-project parser tests](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/parser/PbsQuotedProjectTest.java). diff --git a/discussion/lessons/DSC-0111-pbs-production-reproductions-and-fixes/LSN-0106-pbs-production-binding-and-lowering-corrections.md b/discussion/lessons/DSC-0111-pbs-production-reproductions-and-fixes/LSN-0106-pbs-production-binding-and-lowering-corrections.md index a74ffc0e..516d1175 100644 --- a/discussion/lessons/DSC-0111-pbs-production-reproductions-and-fixes/LSN-0106-pbs-production-binding-and-lowering-corrections.md +++ b/discussion/lessons/DSC-0111-pbs-production-reproductions-and-fixes/LSN-0106-pbs-production-binding-and-lowering-corrections.md @@ -93,4 +93,4 @@ Diagnostic ownership, stable detector IDs, source attribution and failure classi Normative obligations are propagated to PBS [4 — Static Semantics](../../../docs/specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md), [12 — Diagnostics](../../../docs/specs/compiler-languages/pbs/12.%20Diagnostics%20Specification.md), and [13 — Lowering IRBackend](../../../docs/specs/compiler-languages/pbs/13.%20Lowering%20IRBackend%20Specification.md). Existing PBS [3 — Core Syntax](../../../docs/specs/compiler-languages/pbs/3.%20Core%20Syntax%20Specification.md), [5 — Resolution](../../../docs/specs/compiler-languages/pbs/5.%20Manifest%2C%20Stdlib%2C%20and%20SDK%20Resolution%20Specification.md), and [9 — Dynamic Semantics](../../../docs/specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md) remain authoritative for the unchanged language contracts. -Durable regressions live in [PbsProductionLoweringRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsProductionLoweringRegressionTest.java), [PbsNominalOwnerRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/lowering/PbsNominalOwnerRegressionTest.java), and the [unchanged corpus resource](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/resources/production-regressions/cases.json). The maintained [runner guide](../../../tools/pbs-production-corpus/README.md) describes reproduction. DEC-0088 and PLN-0166 are completed control artifacts consolidated here; their workflow files are removed by CLI housekeeping. +Durable regressions live in [PbsProductionLoweringRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsProductionLoweringRegressionTest.java), [PbsNominalOwnerRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/lowering/PbsNominalOwnerRegressionTest.java), and the [unchanged corpus resource](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/resources/production-regressions/cases.json). The maintained [runner guide](../../../../tooling/scripts/pbs-production-corpus/README.md) describes reproduction. DEC-0088 and PLN-0166 are completed control artifacts consolidated here; their workflow files are removed by CLI housekeeping. diff --git a/docs/specs/README.md b/docs/specs/README.md index ef2619c1..c0b5b765 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -29,7 +29,8 @@ See [repository instructions](../../AGENTS.md). ## Navigation verification -Run `python3 tools/documentation/verify.py` from the repository root to check local +Run `../tooling/.venv/bin/python ../tooling/scripts/documentation/verify.py --root .` +from the Studio repository root to check local links and anchors. Pass `--runtime ../runtime` to also check provider references against an available read-only runtime checkout. The byte-exact architecture/ISA mirrors retain the link context of their runtime originals; the checker resolves diff --git a/docs/specs/compiler-languages/pbs/19. Service Constants and Runtime Math Specification.md b/docs/specs/compiler-languages/pbs/19. Service Constants and Runtime Math Specification.md index 2a85b0cc..7e6eb427 100644 --- a/docs/specs/compiler-languages/pbs/19. Service Constants and Runtime Math Specification.md +++ b/docs/specs/compiler-languages/pbs/19. Service Constants and Runtime Math Specification.md @@ -126,4 +126,4 @@ remain separately pending; local results and cross-compilation do not qualify th - [Common runtime catalog support](../../compiler/24.%20Runtime%20Catalog%20Support%20Specification.md) - [Runtime numeric contract](../../../../../runtime/docs/specs/runtime/02d-gameplay-math-and-numeric-semantics.md) -- [Production conformance harness](../../../../tools/pbx-conformance/README.md) +- [Production conformance harness](../../../../../tooling/scripts/pbx-conformance/README.md) diff --git a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md index 4b8598c5..a0aaa63c 100644 --- a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md @@ -903,4 +903,4 @@ Sibling-file callable/global/service surfaces MUST use declaration/signature-lev Nominal receiver/method binding MUST retain the originating declaration and lexical scope, including aliases and synthesized receiver types. A private homonym introduced through a dependency cannot replace a local declaration or create an ambiguous executable target merely by sharing spelling. Transient IDs and PBX byte equality across builds are not nominal-identity requirements. -Conformance: PbsProductionLoweringRegressionTest and PbsNominalOwnerRegressionTest cover the frozen 28-case corpus, contextual overloads, privacy by signature, shared storage/singletons and order-sensitive effects. The maintained source-to-guest matrix is tools/pbs-production-corpus/run.py. +Conformance: PbsProductionLoweringRegressionTest and PbsNominalOwnerRegressionTest cover the frozen 28-case corpus, contextual overloads, privacy by signature, shared storage/singletons and order-sensitive effects. The maintained source-to-guest matrix is ../tooling/scripts/pbs-production-corpus/run.py. diff --git a/docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md b/docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md index fe63d2dd..f1517a17 100644 --- a/docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md +++ b/docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md @@ -187,8 +187,8 @@ frontend syntax and lowering remain consumer-owned. | Stable declarations, nominal identity, structural deduplication and cycles | LinkedRegistryTest; IRBackendExecutableContractTest | pass | Common API and linking | | Complete typed signatures, captures, roles and implementations | PbxRegistryConformanceTest; TypedCommonPipelineTest | pass | Common IR through emission | | Exact PBX mandatory tables and multi-slot signatures | Independent 194-byte oracle; fixed vec2 function bytes | pass | Wire format, not a self round-trip | -| Runtime final admission and execution | tools/pbx-conformance/run.py | pass | Closure, trait, array, Dynamic, intrinsic, roles, joins, native binding; vec2 load-only | -| Invalid structures, references, code and resource refusal | tools/pbx-conformance/main.rs mutation corpus | pass | Production loader, default/lowered limits | +| Runtime final admission and execution | ../tooling/scripts/pbx-conformance/run.py | pass | Closure, trait, array, Dynamic, intrinsic, roles, joins, native binding; vec2 load-only | +| Invalid structures, references, code and resource refusal | ../tooling/scripts/pbx-conformance/main.rs mutation corpus | pass | Production loader, default/lowered limits | | Structured initialization and binding diagnostics | HeadlessProcessSessionTest; observed runtime JSON fixtures | pass | Preserves full payload through MCP, including null outer PC | | Published schema covers current runtime reasons | Actual LifecycleRole/NonFiniteValue payloads against runtime schema | partial | Runtime enum/schema mismatch recorded in AGD75; no payload rewriting | | PBS migration and integrated delivery | AGD75 and consumer tickets | partial | Existing PBS suite passing is not complete executable lowering evidence | diff --git a/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md b/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md index 27e45115..356b6113 100644 --- a/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md +++ b/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md @@ -196,7 +196,7 @@ Run the focused common tests, then the production harness: ```sh ./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' -python3 tools/pbx-conformance/run.py --runtime ../runtime +../tooling/.venv/bin/python ../tooling/scripts/pbx-conformance/run.py --studio . --runtime ../runtime ``` The Java tests write `build/registry-conformance` inside the build-pipeline diff --git a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md index 7d97f1eb..e13a2b2b 100644 --- a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md +++ b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md @@ -6,6 +6,11 @@ Purpose: Define the normative shell structure of the Studio UI. ## Authority and Precedence +This document describes the retained previous frontend. The normal application's +replacement shell/project flow is governed by specifications +[13](13.%20JavaFX%202%20Foundation%20Specification.md) and +[14](14.%20Integrated%20Play%20Specification.md), which take precedence for UI2. + 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 diff --git a/docs/specs/studio/13. JavaFX 2 Foundation Specification.md b/docs/specs/studio/13. JavaFX 2 Foundation Specification.md index 1af5c27c..20c1a63d 100644 --- a/docs/specs/studio/13. JavaFX 2 Foundation Specification.md +++ b/docs/specs/studio/13. JavaFX 2 Foundation Specification.md @@ -1,18 +1,30 @@ # JavaFX 2 Foundation Specification -Status: Implemented foundation. Owner: `studio`. +Status: Implemented foundation and default product frontend. Owner: `studio`. ## Scope and precedence This document governs `prometeu-studio-ui-javafx-2`, an independent replacement frontend foundation. It defines the minimal shell, presentation components, themes, localization and typography. It does not redefine Studio API/Core, MCP, asset banks or runtime contracts. -The existing frontend and its launcher remain available. Specifications 1–4 continue to describe that frontend's current shell/components/workspaces; they are not a visual or architectural template for JavaFX 2. Later capabilities must extend the new foundation through their own explicit contracts. +The normal application now uses this frontend, with project/Play integration owned +by the [Integrated Play Specification](14.%20Integrated%20Play%20Specification.md). +The previous module is retained for consultation and adapter qualification. +Specifications 1–4 describe its shell/components/workspaces; they are not a visual +template for JavaFX 2. Later capabilities must extend the foundation through their +own explicit contracts. ## Shell -The default launch MUST show a native-decorated window with Studio identity, theme/language selectors and an empty central working area. Minimum outer window size is 680×480; the initial scene is 1200×800. Toolbar content MUST wrap/reflow instead of requiring horizontal scrolling at the supported minimum width. +The standalone foundation launch MUST show a native-decorated window with Studio +identity, presentation selectors and an empty working area. The product mounts its +chooser/Play view there. Minimum outer size is 680×480; the foundation initial scene +is 1200×800, and the integrated product starts at 1200×850. Toolbar content MUST +wrap/reflow instead of requiring horizontal scrolling at the minimum width. -The shell MUST NOT initialize a game project, backend service graph, runtime or agent. It MUST NOT contain fictitious editor tabs, operations or domain panels. The component gallery is a separate developer launch, not a product workspace. +The shell component and standalone demonstrations MUST NOT initialize a project, +backend graph, runtime or agent. Product services are injected into a separate +coordinator by the app. There MUST be no fictitious editor tabs or domain panels. +The component gallery is a separate developer launch, not a product workspace. ## Presentation ownership @@ -46,4 +58,8 @@ The foundation MUST have display-free tests of its own locale/preferences/resour Initial qualification is on available macOS. Windows/Linux, assistive-technology walkthroughs and native IME composition require their own evidence. Logical scene snapshots MUST NOT be presented as proof of physical pixel alignment at every HiDPI scale. -Project navigation, document host, free docking, ACP, asset workflows, code/LSP editor, scene/entity authoring, pixels/audio editing and Shipper are outside this foundation contract. Backend integrations MUST use existing application services when those features are introduced; domain logic MUST NOT be duplicated here. +Project navigation and integrated Play are specified separately by specification +14. Document host, free docking, ACP, asset workflows, code/LSP editor, scene/entity +authoring, pixels/audio editing and shipping remain outside this foundation +contract. Backend integrations MUST use existing application services; domain logic +MUST NOT be duplicated here. diff --git a/docs/specs/studio/14. Integrated Play Specification.md b/docs/specs/studio/14. Integrated Play Specification.md new file mode 100644 index 00000000..c4a97b41 --- /dev/null +++ b/docs/specs/studio/14. Integrated Play Specification.md @@ -0,0 +1,149 @@ +# Integrated Play Specification + +Status: Implemented first interactive slice. Owner: `studio`. + +## Product and scope + +The normal `prometeu-app` launcher and managed installation MUST use +`prometeu-studio-ui-javafx-2`. The standalone foundation shell and gallery remain +development entry points. The previous frontend is retained for existing adapter +qualification; its workspaces are not mounted in the new product. + +Startup MUST show known projects and an action to open an existing project +directory. A project MUST be closed before another can open. Closing returns to +the chooser. Startup MUST NOT automatically restore the previous project. + +This slice exposes Play, Pause, Resume, Stop, a game viewport, and bounded logs. +It MUST NOT initialize an AI client or editor/LSP infrastructure when opening for +Play. Existing headless, MCP, evidence, tests and agent contracts remain available +through their existing entry points and services. Their preservation takes +precedence over interactive convenience. + +Project creation UI, editors, workspaces, AI prompts, tuning during Play, +breakpoints, hot reload, PMC builds and distribution/export are outside this +slice. Future packaging belongs in Studio as a separate action; Play MUST NOT +implicitly package a PMC or a distributable runtime. + +## Preparation, process and authority + +Play MUST reuse the compiler/Packer/Shipper preparation pipeline to produce the +cartridge directory. Managed asset capacity, input revision and artifact identity +guards MUST remain enforced against the selected runtime installation. A changed +runtime requires a newly qualified capacity profile; the consumer MUST NOT infer +equivalence from its version string or bypass the guard. + +Core owns execution orchestration and an exclusive project lease. The lease MUST +cover preparation, connection, running, paused and stopping phases until actual +preparation termination and native process/worker cleanup. Other project writes +MUST be rejected at service admission, including writes initiated outside the UI. +Preparation by the execution owner has a scoped admission path; it MUST NOT grant +an arbitrary caller permission to edit. The frontend MUST disable configuration +through the same ownership interval. A state label alone MUST NOT release ownership. + +The application adapter MUST start a direct, owned `prometeu-runtime` child in +interactive `--studio` mode, without a native game window. This does not compile +Rust for the JVM or load native VM code into Java. Wire and process mechanics +belong to `prometeu-app`, behind neutral API/Core ports. UI2 MUST depend only on +Studio API and its presentation toolkit, never Core, concrete providers or the +previous frontend. + +Process/control/video/log workers MUST use a per-connection executor independent +of the bounded operation pool. FX code MUST NOT wait for compilation, sockets, +native process exit or worker joins. Native process completion and worker cleanup +are prerequisites for returning project authority. Failed/stale attempts MUST NOT +change a replacement execution's lifecycle. + +## Lifecycle and focus + +Play prepares, connects, waits for READY, and issues START. Pause freezes logical +game advancement and audio without replacing the machine. Resume continues that +same session. Pause requested during preparation/connection MUST arm a paused +startup; START alone MUST NOT undo it. Stop cancels/waits for preparation or asks +the native host to stop and confirms teardown. + +Minimizing or switching focus to another application MUST pause. Returning focus +or restoring the window MUST NOT automatically resume. Windows/popups owned by +Studio MUST be treated as part of Studio. A focus loss during an asynchronous +Resume MUST still result in pause once the runtime becomes running. + +Closing a project or Studio MUST stop its game before closing the project session. +A normal Stop or close that is refused by save protection MUST retain the paused +session and its lease, explain the refusal in logs, and allow manual Resume. + +Required IPC failure MUST close channels, terminate the owned native process, +retain bounded diagnostics and restore controls after cleanup. There MUST be no +automatic reconnect/restart, process-name-based termination or loss of headless +capabilities as a recovery mechanism. A new Play requires a new explicit action. + +## Save media + +For a game declaring save slots, the human MUST select an existing development +save image or explicitly select a disposable session. The frontend MUST NOT +silently create, overwrite or discard persistent media. The disposable choice is +per Play and MUST NOT be silently restored as a persistent project preference. +Existing agent/indentation setup fields MUST be preserved when runtime/save paths +are saved. + +Normal Stop MUST wait for pending IO or refuse if it cannot finish safely, and +MUST refuse uncommitted persistent data. Disposable Stop may discard only because +that session was explicitly selected. IPC failure is the bounded forced-teardown +exception; it MUST be reported rather than represented as a successful save. + +## Presentation and input + +The binary [Studio Play protocol](../../../../runtime/docs/specs/runtime/11b-studio-play-protocol.md) +uses independent control/input and video channels, bounded messages, session and +epoch correlation, and one video credit returned after full reception. The native +tick MUST NOT wait for FX or socket writes. Unsent presentation frames may be +replaced by the latest complete publication; partial wire messages MUST finish or +fail. Control messages MUST NOT be dropped as a presentation optimization. + +Java reception converts RGBA8 to premultiplied BGRA on an IO worker. Three CPU +buffers have explicit free, receiving, pending and presentation ownership, with +at most one presentation lease. A leased image MUST remain stable until close. +FX polls the latest complete frame on a pulse, copies it to an FX-owned +`WritableImage`, and releases the lease. Reception MUST NOT enqueue one FX task +per frame. Logs and frontend projections MUST remain bounded. + +Zoom choices MUST be x1, x2 and x4 with nearest-neighbor presentation. At x1 a +480×270 game occupies 480×270 logical pixels, respecting OS scale; it does not mean +one physical display pixel. Oversized images MUST retain zoom and scroll. The UI +MUST NOT silently fit the image or change zoom. + +Input MUST invert the image's scene transform and selected logical zoom. Touch +outside the image MUST release/reject touch rather than clamp to an edge. Keyboard +input belongs to the focused viewport, with modifiers reserved for application +shortcuts. Pad keys are arrows, A/D/W/S for A/B/X/Y, Q/E for L/R, Z for Start and +Shift for Select. Focus loss and lifecycle changes MUST neutralize held input; +native epochs reject input from older execution phases. + +## Verification and limits + +The product baseline is Java 25, retaining JavaFX 23.0.2. The bundled image uses an +explicit JDK `jmods` module path for jlink. Build logic may target Java 21 bytecode; +that is not the Studio application baseline. + +Qualification MUST cover actual installed startup, existing-game image/input, +pause/resume and focus, project close, dirty-save refusal and cross-mode readback, +broken channels, slow presentation/receiver, bounded buffers, repeated sessions, +and preserved headless/MCP/evidence/tests. Codec fixtures alone are insufficient. + +`studioPlayDesktopTest` is an opt-in desktop gate. `-PstudioPlayStress=true` adds a +30-second idle-host measurement, deliberate FX suspension and twenty cycles. +Receive-to-copy latency uses `System.nanoTime` in the same JVM; it MUST NOT be +called end-to-end input latency or physical scanout latency. CPU/heap observations +and hardware/OS/build flavor MUST accompany performance claims. A heap-used sample +does not prove retained-memory bounds; ownership and resource tests do. + +Executed functional qualification includes macOS ARM64 with Java 25 and the release +umbrella distribution produced by `runtime/scripts/local-dist.sh`, including real +Pong Play and the deterministic headless process. Capacity qualification identifies +the dispatcher and both native backends as one exact bundle; multiple releases may +share an unchanged dispatcher. The explicit qualification command is documented in +the [Studio README](../../../README.md). + +Earlier presentation performance measurements used debug native binaries. +Windows/Linux, release performance, physical HiDPI pixel alignment, and human +listening/IME/accessibility walkthroughs require separate evidence. Diagnostic runs +and failures remain in Work evidence; a later passing run does not establish their +unobserved cause. diff --git a/docs/specs/studio/8. Project-Local Studio State Specification.md b/docs/specs/studio/8. Project-Local Studio State Specification.md index ca932c91..6a23931d 100644 --- a/docs/specs/studio/8. Project-Local Studio State Specification.md +++ b/docs/specs/studio/8. Project-Local Studio State Specification.md @@ -20,6 +20,13 @@ Define the normative contract for Studio project-local persistence under `.studi ## Authority and Precedence +The new Play frontend preserves stored workspace state but does not mount or +restore previous workspaces and never automatically opens the last project. +Runtime/save path updates preserve indentation and agent intent. Presentation +preferences remain separate from `.studio/state.json`; disposable save selection +is an explicit per-Play choice. See specification +[14](14.%20Integrated%20Play%20Specification.md). + This specification implements the accepted decision for project-local Studio state under `.studio/`. It extends: diff --git a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md index e796c55f..0a460066 100644 --- a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md +++ b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md @@ -9,6 +9,7 @@ Active - `prometeu-studio-api` - `prometeu-studio-core` - `prometeu-studio-ui-javafx` +- `prometeu-studio-ui-javafx-2` - `prometeu-app` - integrations with compiler, Packer, LSP, and the runtime @@ -47,6 +48,15 @@ JavaFX is the human adapter; DEV is its authorization and observation workspace. 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 normal app composes UI2 through neutral API services; the previous adapter +remains for compatibility qualification. Interactive execution adds neutral +pause/resume, input, stable frame leases and ownership queries. Core owns exclusive +admission through preparation and confirmed teardown. Binary TCP framing, native +process ownership and IO workers belong to the app adapter, independently of the +deterministic headless gateway. `openForPlay` defers editor/agent infrastructure; +the existing session path and automation contracts remain. See specification +[14](14.%20Integrated%20Play%20Specification.md). + The legacy mixed `prometeu-studio` module and the static `p.studio.Container` service locator MUST NOT exist in the final architecture. ## API Neutrality diff --git a/docs/specs/studio/README.md b/docs/specs/studio/README.md index 423b4021..1d84ff7a 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -4,15 +4,18 @@ Owner: `studio`. Canonical source: `docs/specs/studio`. This directory contains the normative Studio specification set. -## JavaFX 2 foundation +## Default JavaFX 2 frontend [`13. JavaFX 2 Foundation Specification.md`](13.%20JavaFX%202%20Foundation%20Specification.md) -defines the independent `prometeu-studio-ui-javafx-2` foundation and minimal shell. +defines the `prometeu-studio-ui-javafx-2` foundation and reusable shell. Its [module guide](../../../prometeu-studio-ui-javafx-2/README.md) documents execution, component ownership, themes, locales, bundled fonts and verification. The previous -frontend remains available; specifications 1–4 describe its existing behavior and +frontend is retained for adapter qualification; specifications 1–4 describe its behavior and do not impose its visual structure on the new implementation. Backend contracts -remain shared and unchanged. +remain shared. The normal/installed app uses the new chooser and Play frontend; +[`14. Integrated Play Specification.md`](14.%20Integrated%20Play%20Specification.md) +owns project flow, execution authority, transport/presentation, input, saves and +qualification boundaries. ## Purpose diff --git a/docs/vm-arch/README.md b/docs/vm-arch/README.md index 3d345c42..39eb1ecb 100644 --- a/docs/vm-arch/README.md +++ b/docs/vm-arch/README.md @@ -43,7 +43,7 @@ architecture mirrors are synchronized or that all PBS facades are implemented. Run the explicit source/exporter verification from the Studio root: ```sh -python3 tools/runtime-catalog/verify.py --runtime ../runtime +../tooling/.venv/bin/python ../tooling/scripts/runtime-catalog/verify.py --studio . --runtime ../runtime ``` This command requires a clean checkout of the recorded provider revision, compares diff --git a/files/config/Jenkinsfile b/files/config/Jenkinsfile index d1f6489e..ac8a8cbc 100644 --- a/files/config/Jenkinsfile +++ b/files/config/Jenkinsfile @@ -24,6 +24,7 @@ pipeline { script { env.TESTS_STARTED = 'true' } withChecks(name: 'Test', includeStage: true) { withGradle { + // test excludes the integration tag; tooling owns integration execution. // --continue finishes independent tests/reports but retains a nonzero exit on failure. sh './gradlew test jacocoTestReport --continue --parallel --max-workers=2 --build-cache --no-daemon --console=plain' } @@ -42,8 +43,8 @@ pipeline { junit testResults: '**/build/test-results/test/TEST-*.xml', checksName: 'Test / Tests and coverage', allowEmptyResults: env.VERIFICATION_SUCCEEDED != 'true' - if (env.VERIFICATION_SUCCEEDED == 'true' && !fileExists('prometeu-packer/prometeu-packer-v1/build/test-results/test/TEST-p.packer.services.PackerAssetContractTest.xml')) { - error 'Successful verification is missing the packer contract test report.' + if (env.VERIFICATION_SUCCEEDED == 'true' && !fileExists('prometeu-packer/prometeu-packer-v1/build/test-results/test/TEST-p.packer.services.PackerAssetDeclarationParserTest.xml')) { + error 'Successful verification is missing the packer unit test report.' } } catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { diff --git a/files/config/README.md b/files/config/README.md index b0bdd618..c6d21308 100644 --- a/files/config/README.md +++ b/files/config/README.md @@ -2,16 +2,17 @@ `Jenkinsfile` uses the checked-in Gradle wrapper (currently 9.3.1). A compatible Java installation must be available to launch Gradle; project conventions select -Java 21 for compilation/tests. The pipeline retains its existing Gradle cache +Java 25 for compilation/tests and the product runtime. Build logic targets Java 21 +bytecode independently. The pipeline retains its existing Gradle cache location, worker limit and installed Jenkins report plugins. It does not require a named Jenkins Gradle installation. The build runs on a Unix agent with Java and dependency/cache access. It sets `JAVA_TOOL_OPTIONS=-Djava.awt.headless=true` for Gradle and test JVMs. No display, runtime binary, sibling runtime checkout, runtime download/build, or new Jenkins -plugin is required by the packer contract suite. +plugin is required by the unit suite. -## Commands +## Unit pipeline commands ```sh export JAVA_TOOL_OPTIONS=-Djava.awt.headless=true @@ -22,8 +23,18 @@ export JAVA_TOOL_OPTIONS=-Djava.awt.headless=true Clean is a separate stage: when it fails, old reports must not be published as a new test run. Gradle `--continue` lets independent tasks and reports finish after a test failure; it does not turn a failing command into success. Runtime/desktop -opt-in test tasks are not invoked. The ordinary packer `test` task includes -`PackerAssetContractTest` without skips or a runtime fallback. +opt-in test tasks are not invoked. All ordinary `test` tasks exclude the JUnit +`integration` tag. Tests involving real process, network, desktop, application +composition or cross-provider pipelines are tagged explicitly, including fixture +subprocesses. This exclusion applies even when optional environment variables are +set. Existing integration suites remain in this repository; `../tooling` prepares +their environment and orchestrates selected integration commands and builds. +No integration suite is executed by the repository pipeline. + +The required packer unit report is `PackerAssetDeclarationParserTest`. +`PackerAssetContractTest` is integration-tagged and is not a prerequisite of this +unit-only pipeline. Consolidated coverage consumes only `build/jacoco/test.exec` +from each Java subproject; opt-in integration `.exec` files cannot inflate it. ## Failure reporting @@ -48,8 +59,9 @@ and any available test results. Artifacts follow the Jenkins job's build/artifac retention policy. An otherwise successful verification must produce JUnit results, the packer -contract suite report, consolidated JaCoCo XML and HTML. Missing successful-build -evidence fails publication. A failed compilation may have no reports: the +unit suite report, consolidated JaCoCo XML and HTML. Missing successful-build +evidence fails publication. The required packer report is the unit parser suite. +A failed compilation may have no reports: the original build failure remains authoritative and available diagnostics are still preserved. A failed clean does not publish potentially stale artifacts. @@ -60,9 +72,10 @@ test runs are useful diagnostics, not a passing quality gate. ## Contract and manual verification boundary See the packer fixture [provenance and coverage](../../prometeu-packer/prometeu-packer-v1/src/test/resources/fixtures/contracts/README.md). -The automated suite checks producer bytes and metadata against independent -expectations. Runtime gameplay remains manual with existing games, not a local -or CI automated test. Record manual outcomes only after execution. +The retained integration contract suite checks producer bytes and metadata against +independent expectations. It is excluded from this unit pipeline. Runtime gameplay +and installed-process verification remain separate integration/desktop checks for +the tooling repository; record their outcomes only after explicit execution. Local Gradle checks and Groovy parsing cannot certify controller plugin behavior. A Jenkins run is needed to observe actual report publication and coverage checks; diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ee11348c..6ab50409 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,8 +2,8 @@ javafx = "23.0.2" richtextfx = "0.11.2" jackson = "2.18.2" -jacoco = "0.8.12" -lombok = "1.18.32" +jacoco = "0.8.14" +lombok = "1.18.42" junit-jupiter = "5.12.1" archunit = "1.4.2" slf4j = "2.0.7" diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index b9c62297..fcd33719 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -3,6 +3,9 @@ plugins { alias(libs.plugins.javafx) } +// Configure the application-capable UI module before lazy classpath queries configure it. +evaluationDependsOn(":prometeu-studio-ui-javafx-2") + dependencies { implementation(libs.tomlj) implementation(project(":prometeu-infra")) @@ -17,6 +20,7 @@ dependencies { implementation(project(":prometeu-studio-api")) implementation(project(":prometeu-studio-core")) implementation(project(":prometeu-studio-ui-javafx")) + implementation(project(":prometeu-studio-ui-javafx-2")) implementation(libs.spring.boot) implementation(libs.lsp4j) implementation(libs.javafx.controls) @@ -25,9 +29,10 @@ dependencies { application { mainClass = "p.studio.app.StudioLauncher" + applicationDefaultJvmArgs = listOf("--enable-native-access=ALL-UNNAMED") } -val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) } +val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } val studioRuntime = layout.buildDirectory.dir("studio-runtime") val assembleStudioRuntime by tasks.registering(Exec::class) { val jdk = studioJava.get().metadata.installationPath.asFile @@ -40,11 +45,16 @@ val assembleStudioRuntime by tasks.registering(Exec::class) { check(it.setWritable(true, true)) { "Cannot normalize staged runtime permissions" } } } - commandLine(jdk.resolve("bin/jlink"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files", + commandLine(jdk.resolve("bin/jlink"), "--module-path", jdk.resolve("jmods"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files", "--no-man-pages", "--output", studioRuntime.get().asFile) } distributions { - main { contents { from(assembleStudioRuntime) { into("runtime") } } } + main { contents { + from(assembleStudioRuntime) { into("runtime") } + from(project(":prometeu-studio-ui-javafx-2").file("src/main/resources/p/studio/ui/javafx2/fonts")) { + include("*-LICENSE.txt");into("licenses") + } + } } } tasks.register("stageStudioInstallation") { group = "application" @@ -121,6 +131,7 @@ tasks.register("headlessProcessTest") { project(":prometeu-compiler:prometeu-build-pipeline").layout.buildDirectory.dir("registry-conformance").get().asFile.absolutePath) include("**/HeadlessTaskIntegrationTest.class") systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) + systemProperty("studio.test.pong", rootProject.file("test-projects/pong").absolutePath) } tasks.register("memcardProcessTest") { @@ -149,8 +160,41 @@ tasks.register("headlessMcpDesktopTest") { // Subprocess tests exercise the actual Studio main and OS ownership boundaries. tasks.withType().configureEach { systemProperty("studio.test.classpath", sourceSets["test"].runtimeClasspath.asPath) + systemProperty("studio.test.protocolFixtures", rootProject.file("../runtime/devtools/studio-protocol/fixtures").absolutePath) + systemProperty("studio.test.studioHost", providers.gradleProperty("studioPlayHost").getOrElse( + rootProject.file("../runtime/target/debug/prometeu-host-desktop-winit" + if (System.getProperty("os.name").startsWith("Windows")) ".exe" else "").absolutePath)) + systemProperty("studio.test.studioCartridge", rootProject.file("../runtime/test-cartridges/dummy-boy").absolutePath) } +tasks.named("test") { exclude("**/StudioPlayProcessTest.class") } +tasks.named("test") { exclude("**/StudioPlayDesktopTest.class") } +tasks.register("studioPlayDesktopTest") { + group = "verification" + description = "Qualifies the default Play frontend with an installed native runtime and a desktop." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/StudioPlayDesktopTest.class") + systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) + systemProperty("studio.test.pong", rootProject.file("test-projects/pong").absolutePath) + systemProperty("studio.test.playStress", providers.gradleProperty("studioPlayStress").getOrElse("false")) + systemProperty("java.awt.headless", "false") + outputs.upToDateWhen { false } + testLogging.showStandardStreams = true +} +tasks.register("studioPlayProcessTest") { + group = "verification" + description = "Qualifies real interactive binary IPC (requires the Studio host binary, no display)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/StudioPlayProcessTest.class") + include("**/StudioPlayInstalledRuntimeTest.class") + systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) + outputs.upToDateWhen { false } +} +tasks.named("test") { exclude("**/StudioPlayInstalledRuntimeTest.class") } + tasks.named("test") { exclude("**/InstalledConnectorTest.class") } tasks.register("installedConnectorTest") { group = "verification" @@ -191,6 +235,9 @@ tasks.named("test") { exclude("**/AssetCapacityInstalledRuntimeTest.class" tasks.register("assetCapacityProcessTest") { group = "verification" description = "Qualifies glyph/scene 16/17 boundaries against the exact installed runtime." + // The selected installation is external and can be rebuilt at the same path. + outputs.upToDateWhen { false } + outputs.doNotCacheIf("Qualification must observe the currently installed native binaries") { true } testClassesDirs = sourceSets["test"].output.classesDirs classpath = sourceSets["test"].runtimeClasspath useJUnitPlatform() diff --git a/prometeu-app/src/main/java/p/studio/app/App.java b/prometeu-app/src/main/java/p/studio/app/App.java index 8a76e33e..7e2e21ea 100644 --- a/prometeu-app/src/main/java/p/studio/app/App.java +++ b/prometeu-app/src/main/java/p/studio/app/App.java @@ -5,11 +5,11 @@ 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; +import p.studio.ui.javafx2.window.StudioWindowCoordinator2; public class App extends Application { private ConfigurableApplicationContext applicationContext; - private StudioWindowCoordinator studioWindowCoordinator; + private StudioWindowCoordinator2 studioWindowCoordinator; @Override public void init() throws Exception { @@ -18,11 +18,12 @@ public class App extends Application { .web(WebApplicationType.NONE) .headless(false) .run(); + applicationContext.getBean(StudioUiFactory.class).prepareInteractive(); } @Override public void start(Stage stage) { - studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).create(stage); + studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).createInteractive(stage); studioWindowCoordinator.showLauncher(); } diff --git a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java index 26af9e7b..6608d6d3 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -323,7 +323,9 @@ public class StudioApplicationConfiguration { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, p.studio.api.assets.animation.AnimationService animationService) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, + p.studio.api.assets.animation.AnimationService animationService,ObjectMapper mapper,OperationExecutor operations, + p.studio.core.project.ProjectAccessRegistry access,ProjectLocalStudioSetupStore setupStore) { var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory, executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, @@ -331,6 +333,9 @@ public class StudioApplicationConfiguration { tiledAssetService, sceneBankWorkflow, windowStateStore, activityHistoryStore, connectionGuide); factory.setAnimationService(animationService); + factory.enableInteractive(new p.studio.core.execution.DefaultExecutionControllerFactory(shipper, + new p.studio.app.runtime.studio.StudioRuntimeGateway(mapper),operations,access), + (project,setup)->{try(var lease=access.enterManual(project.rootPath())){setupStore.save(project,setup);}}); return factory; } diff --git a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java index d569efe8..7516d3b5 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java @@ -31,6 +31,19 @@ import p.studio.ui.javafx.utilities.i18n.I18nService; import p.studio.ui.javafx.events.StudioEventBus; public final class StudioUiFactory { + private ExecutionControllerFactory interactiveExecutions; + private java.util.function.BiConsumer setupSaver; + private p.studio.ui.javafx2.window.WindowResources interactiveResources; + public void enableInteractive(ExecutionControllerFactory factory, + java.util.function.BiConsumer saver) { + interactiveExecutions=Objects.requireNonNull(factory);setupSaver=Objects.requireNonNull(saver); + } + public void prepareInteractive(){interactiveResources=new p.studio.ui.javafx2.window.WindowResources();} + public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){ + if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized"); + return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory, + Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources); + } private final ProjectCatalog projectCatalog; private final KnownProjects knownProjects; private final ProjectLanguageCatalog languageCatalog; diff --git a/prometeu-app/src/main/java/p/studio/app/assets/AssetCapacityProfiles.java b/prometeu-app/src/main/java/p/studio/app/assets/AssetCapacityProfiles.java index 2ae8fc36..2ca783ba 100644 --- a/prometeu-app/src/main/java/p/studio/app/assets/AssetCapacityProfiles.java +++ b/prometeu-app/src/main/java/p/studio/app/assets/AssetCapacityProfiles.java @@ -5,35 +5,55 @@ import p.studio.api.assets.AssetBudgets.*; import p.studio.api.project.ProjectLocalStudioSetup; import java.nio.file.*; import java.util.*; +import java.io.InputStream; +import java.util.function.Function; /** Installed resource profiles only. Ordinary builds never inspect a sibling runtime checkout. */ public final class AssetCapacityProfiles { public record Bundle(Profile profile,Map executables){} public record Catalog(int schemaVersion,List profiles){} private final ObjectMapper json; - public AssetCapacityProfiles(ObjectMapper json){this.json=json;} + private static final Set EXECUTABLES = Set.of("prometeu", "prometeu-headless", "prometeu-runtime"); + private final Function resources; + public AssetCapacityProfiles(ObjectMapper json){this(json, name -> AssetCapacityProfiles.class.getClassLoader().getResourceAsStream(name));} + AssetCapacityProfiles(ObjectMapper json, Function resources){this.json=json;this.resources=resources;} public ProfileSelection select(ProjectLocalStudioSetup setup) { if(setup==null||setup.prometeuRuntimePath()==null)return ProfileSelection.unknown(null,"No runtime installation selected"); String selected=null; try { - Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=System.getProperty("os.name").startsWith("Windows")?"prometeu.exe":"prometeu"; + Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=executable("prometeu"); selected=AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(dispatcher))); - try(var stream=getClass().getResourceAsStream("/asset-capacity/catalog.json")) { + var actual = new HashMap(); + actual.put("prometeu", selected); + String mismatch = null; + try(var stream=resources.apply("asset-capacity/catalog.json")) { if(stream==null)return ProfileSelection.unknown(selected,"No distributed capacity profiles"); var catalog=json.readValue(stream,Catalog.class);if(catalog.schemaVersion()!=1)throw new IllegalArgumentException("Unsupported profile catalog"); for(var bundle:catalog.profiles())if(bundle.profile().executableSha256().equals(selected)) { - if(!bundle.executables().keySet().containsAll(Set.of("prometeu","prometeu-headless","prometeu-runtime")))throw new IllegalArgumentException("Incomplete executable identity"); + if(!bundle.executables().keySet().equals(EXECUTABLES))throw new IllegalArgumentException("Incomplete or unsupported executable identity"); + String changed = null; for(var entry:bundle.executables().entrySet()) { - if(!Set.of("prometeu","prometeu-headless","prometeu-runtime").contains(entry.getKey()))throw new IllegalArgumentException("Unsupported executable identity"); - if(!AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(entry.getKey()))).equals(entry.getValue()))return ProfileSelection.unknown(selected,"Runtime component changed: "+entry.getKey()); + String hash = actual.get(entry.getKey()); + if(hash == null) { + hash = AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(executable(entry.getKey())))); + actual.put(entry.getKey(), hash); + } + if(!hash.equals(entry.getValue())) { changed = entry.getKey(); break; } } - for(var evidence:bundle.profile().evidence())try(var record=getClass().getClassLoader().getResourceAsStream(evidence.evidencePath())) { + // Several qualified releases may legitimately share an unchanged dispatcher. + // Never combine backend identities from separate catalog entries. + if(changed != null) { mismatch = "Runtime component changed: " + changed + "; no complete qualified bundle matched"; continue; } + for(var evidence:bundle.profile().evidence())try(var record=resources.apply(evidence.evidencePath())) { if(record==null||!AssetWorkspaceFiles.hash(record.readAllBytes()).equals(evidence.evidenceSha256()))throw new IllegalArgumentException("Capacity evidence integrity mismatch"); } return new ProfileSelection(QualificationState.known,selected,bundle.profile(),"Exact qualified dispatcher and runtime components match"); } } + if(mismatch != null)return ProfileSelection.unknown(selected,mismatch); return ProfileSelection.unknown(selected,"Selected executable has no qualified capacity profile"); }catch(Exception invalid){return ProfileSelection.unknown(selected,"Capacity profile unavailable or invalid: "+Objects.requireNonNullElse(invalid.getMessage(),invalid.getClass().getSimpleName()));} } + private static String executable(String name) { + return name + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : ""); + } } diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/studio/LatestFramePool.java b/prometeu-app/src/main/java/p/studio/app/runtime/studio/LatestFramePool.java new file mode 100644 index 00000000..88dd3e4b --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/studio/LatestFramePool.java @@ -0,0 +1,48 @@ +package p.studio.app.runtime.studio; + +import p.studio.api.execution.ExecutionFrame; +import java.io.IOException; +import java.util.ArrayDeque; + +/** Three CPU buffers; at most one presentation lease, independent of reception. */ +final class LatestFramePool implements AutoCloseable { + private final int width,height; + private final ArrayDeque free=new ArrayDeque<>(3); + private Pending pending; + private boolean leased,closed; + private record Pending(byte[] pixels,long id,long epoch,long receivedAt) { } + LatestFramePool(int width,int height)throws IOException { + this.width=width;this.height=height; + int size=StudioWire.frameBytes(width,height,width); + for(int i=0;i<3;i++)free.add(new byte[size]); + } + synchronized byte[] receive()throws IOException { + if(closed)throw new IOException("Video pool closed"); + byte[] pixels=free.poll(); + if(pixels==null)throw new IOException("Video ownership exhausted"); + return pixels; + } + synchronized void recycle(byte[] pixels){if(!closed)free.add(pixels);} + synchronized void publish(byte[] pixels,long id,long epoch){ + publish(pixels,id,epoch,System.nanoTime()); + } + synchronized void publish(byte[] pixels,long id,long epoch,long receivedAt){ + if(closed)return; + if(pending!=null)free.add(pending.pixels()); + pending=new Pending(pixels,id,epoch,receivedAt); + } + synchronized ExecutionFrame acquire(){ + if(closed||leased||pending==null)return null; + Pending owned=pending;pending=null;leased=true; + return new ExecutionFrame(width,height,owned.id(),owned.epoch(),owned.pixels(),owned.receivedAt(),()->{ + synchronized(this){leased=false;if(!closed)free.add(owned.pixels());} + }); + } + @Override public synchronized void close(){closed=true;pending=null;free.clear();} + static void rgbaToBgraPre(byte[] pixels){ + for(int i=0;i logs; + private final Executor executor; + private final CompletableFuture completion=new CompletableFuture<>(); + private final CompletableFuture stopped=new CompletableFuture<>(); + private final ScheduledExecutorService timer=Executors.newSingleThreadScheduledExecutor(r->{ + Thread t=new Thread(r,"studio-play-heartbeat");t.setDaemon(true);return t; + }); + private final ArrayBlockingQueue outgoing=new ArrayBlockingQueue<>(256); + private final ConcurrentMap pending=new ConcurrentHashMap<>(); + private final AtomicBoolean closing=new AtomicBoolean(),failed=new AtomicBoolean(); + private final AtomicLong epoch=new AtomicLong(1); + private final AtomicInteger state=new AtomicInteger(); + private final List> workers=new ArrayList<>(); + private volatile long lastControl=System.nanoTime(); + private volatile Throwable failure; + private volatile boolean expectedEnd; + private long nextRequest; + private volatile long stopRequest; + private CompletableFuture stopResult; + private record Packet(int kind,long request,byte[] payload) { } + private record Pending(int kind,long deadline,CompletableFuture result) { } + + StudioRuntimeConnection(Process process,Socket control,Socket video,Reader controlReader,Reader videoReader, + byte[] session,int width,int height,Consumer logs,Executor executor, + CompletableFuture stdout,CompletableFuture stderr)throws IOException { + this.process=process;this.control=control;this.video=video;this.controlReader=controlReader;this.videoReader=videoReader; + this.session=session.clone();this.width=width;this.height=height;this.logs=logs;this.executor=executor; + writer=new Writer(control.getOutputStream());frames=new LatestFramePool(width,height); + workers.add(CompletableFuture.runAsync(this::writeLoop,executor)); + workers.add(CompletableFuture.runAsync(this::controlLoop,executor)); + workers.add(CompletableFuture.runAsync(this::videoLoop,executor)); + timer.scheduleAtFixedRate(this::heartbeat,1,1,TimeUnit.SECONDS); + executor.execute(()->{ + try{ + int code=process.waitFor(); + // Drain the terminal control message before closing the other channel. + // TCP ordering is per channel; video EOF can race STOPPED on control. + if(code==0&&stopRequest!=0&&!failed.get()){ + try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception missing){fail(new IOException("Runtime exited without STOPPED",missing));} + } + closing.set(true);state.set(4);timer.shutdownNow();closeSockets();frames.close(); + for(Pending p:pending.values())p.result().completeExceptionally(new IOException("Runtime exited"));pending.clear(); + for(var worker:workers)await(worker);await(stdout);await(stderr); + logs.accept(code==0?RuntimeLogEntry.info("Runtime stopped."):RuntimeLogEntry.error("Runtime exit code "+code)); + Throwable why=failure; + if(why==null)completion.complete(code);else completion.completeExceptionally(why); + if(!stopped.isDone())stopped.completeExceptionally(why==null?new IOException("Runtime exited before STOPPED"):why); + }catch(InterruptedException interrupted){Thread.currentThread().interrupt();fail(interrupted);completion.completeExceptionally(interrupted);} + }); + } + @Override public CompletableFuture completion(){return completion;} + @Override public CompletableFuture startExecution(){return command(START);} + @Override public CompletableFuture pause(){return command(PAUSE);} + @Override public CompletableFuture resume(){return command(RESUME);} + @Override public synchronized CompletableFuture stopAsync(){ + if(completion.isDone())return completion.thenApply(code->{if(code!=0)throw new CompletionException(new IOException("Runtime exit "+code));return null;}); + if(stopResult!=null)return stopResult; + CompletableFuture accepted=command(STOP); + stopResult=accepted.thenCompose(v->stopped).thenCompose(v->completion).thenApply(code->{ + if(code!=0)throw new CompletionException(new IOException("Runtime exit "+code));return (Void)null; + }).orTimeout(5,TimeUnit.SECONDS); + CompletableFuture result=stopResult; + result.whenComplete((v,e)->{ + Throwable why=root(e); + if(why instanceof RuntimeStopRefusedException){synchronized(this){if(stopResult==result)stopResult=null;}} + else if(e!=null)fail(why); + }); + return result; + } + @Override public void close(){try{stopAsync().join();}catch(CompletionException e){ + if(root(e) instanceof RuntimeException runtime)throw runtime;throw e;}} + @Override public ExecutionFrame acquireLatestFrame(){return frames.acquire();} + @Override public void input(ExecutionInput input){ + if(state.get()!=1||closing.get()||failed.get())return; + if((input.buttons()&4096)!=0&&(input.touchX()<0||input.touchY()<0||input.touchX()>=width||input.touchY()>=height)) + throw new IllegalArgumentException("Touch outside game image"); + enqueue(new Packet(INPUT,0,little(20).putLong(epoch.get()).putShort((short)input.buttons()).putShort((short)0) + .putInt(input.touchX()).putInt(input.touchY()).array())); + } + private synchronized CompletableFuture command(int kind){ + if(closing.get()||failed.get())return CompletableFuture.failedFuture(new IOException("Runtime connection closed")); + long id=++nextRequest; + if(kind==STOP)stopRequest=id; + var future=new CompletableFuture(); + pending.put(id,new Pending(kind,System.nanoTime()+TimeUnit.SECONDS.toNanos(5),future)); + enqueue(new Packet(kind,id,new byte[0]));return future; + } + private void enqueue(Packet packet){if(!outgoing.offer(packet))fail(new IOException("Runtime control queue saturated"));} + private void writeLoop(){ + try{while(!closing.get()&&!failed.get()){ + Packet p=outgoing.poll(100,TimeUnit.MILLISECONDS);if(p!=null)writer.send(p.kind(),p.request(),p.payload()); + }}catch(InterruptedException e){Thread.currentThread().interrupt();if(!closing.get())fail(e);} + catch(IOException e){if(!closing.get()&&!expectedEnd)fail(e);} + } + private void controlLoop(){ + try{while(!closing.get()){ + Message m=controlReader.receive();lastControl=System.nanoTime(); + switch(m.header().kind()){ + case RESULT->result(m); + case PONG->{ + if(m.payload().length!=20||m.header().request()!=0)throw new IOException("Invalid PONG"); + var p=ByteBuffer.wrap(m.payload()).order(ByteOrder.LITTLE_ENDIAN); + long e=p.getLong();p.getLong();int s=p.getInt(); + if(e==0||s<0||s>2)throw new IOException("Invalid PONG state"); + } + case ERROR->{String text=text(m.payload(),0);logs.accept(RuntimeLogEntry.error(text));fail(new IOException(text));return;} + case STOPPED->{if(m.payload().length!=0||m.header().request()!=stopRequest||stopRequest==0) + throw new IOException("Unexpected STOPPED");expectedEnd=true;stopped.complete(null);return;} + default->throw new IOException("Unexpected runtime control message"); + } + }}catch(IOException|RuntimeException e){if(!closing.get()&&!expectedEnd)fail(e);} + } + private void result(Message message)throws IOException { + byte[] p=message.payload();if(p.length<20)throw new IOException("Invalid command result"); + var b=ByteBuffer.wrap(p).order(ByteOrder.LITTLE_ENDIAN); + int kind=Short.toUnsignedInt(b.getShort()),status=Short.toUnsignedInt(b.getShort()); + long nextEpoch=b.getLong();b.getLong();String text=text(p,20); + Pending request=pending.remove(message.header().request()); + if(request==null||request.kind()!=kind||status>2||nextEpoch==0)throw new IOException("Uncorrelated runtime result"); + epoch.set(nextEpoch); + if(status==0){switch(kind){ + case START->state.compareAndSet(0,1);case RESUME->state.set(1);case PAUSE,STOP->state.set(2);default->{}} + request.result().complete(null); + }else if(status==2&&kind==STOP){state.set(2);stopRequest=0;request.result().completeExceptionally(new RuntimeStopRefusedException(text));} + else request.result().completeExceptionally(new IllegalStateException(text)); + } + private void videoLoop(){ + byte[] metadata=new byte[FRAME_METADATA_BYTES]; + try{while(!closing.get()){ + Header h=videoReader.nextHeader(); + if(h.kind()!=FRAME||h.length()=0){ + LatestFramePool.rgbaToBgraPre(pixels);frames.publish(pixels,id,frameEpoch,receivedAt);published=true; + } + enqueue(new Packet(FRAME_RECEIVED,0,little(16).putLong(frameEpoch).putLong(id).array())); + }finally{if(!published)frames.recycle(pixels);} + }}catch(IOException|RuntimeException e){ + if(!closing.get()&&!expectedEnd){ + if(stopRequest!=0){ + try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception incomplete){if(!closing.get()&&!expectedEnd)fail(e);} + }else fail(e); + } + } + } + private void heartbeat(){ + if(closing.get()||failed.get())return; + long now=System.nanoTime(); + if(now-lastControl>TimeUnit.SECONDS.toNanos(5)){fail(new IOException("Runtime control heartbeat expired"));return;} + for(Pending p:pending.values())if(now-p.deadline()>0){fail(new IOException("Runtime command timed out"));return;} + enqueue(new Packet(PING,0,new byte[0])); + } + private void fail(Throwable why){ + if(closing.get()||!failed.compareAndSet(false,true))return; + failure=why;state.set(4);logs.accept(RuntimeLogEntry.error("Runtime connection failed: "+why.getMessage())); + for(Pending p:pending.values())p.result().completeExceptionally(why);pending.clear(); + stopped.completeExceptionally(why);closeSockets();frames.close();timer.shutdownNow(); + // Process identity is owned by this connection; never search or kill by executable name. + executor.execute(()->{ + process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly(); + try{if(!process.waitFor(2,TimeUnit.SECONDS)){ + process.destroyForcibly();if(!process.waitFor(2,TimeUnit.SECONDS))logs.accept(RuntimeLogEntry.error("Runtime termination is not confirmed")); + }}catch(InterruptedException e){Thread.currentThread().interrupt();} + }); + } + private void closeSockets(){StudioRuntimeGateway.close(control);StudioRuntimeGateway.close(video);} + private static void await(CompletableFuture work){try{work.join();}catch(CompletionException|CancellationException ignored){}} + private static Throwable root(Throwable failure){ + while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();return failure; + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/studio/StudioRuntimeGateway.java b/prometeu-app/src/main/java/p/studio/app/runtime/studio/StudioRuntimeGateway.java new file mode 100644 index 00000000..ffa350a4 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/studio/StudioRuntimeGateway.java @@ -0,0 +1,121 @@ +package p.studio.app.runtime.studio; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.execution.PlayOptions; +import p.studio.api.project.*; +import p.studio.api.runtime.RuntimeLogEntry; +import p.studio.core.runtime.*; +import p.studio.core.project.ProjectCartridgeConfiguration; +import java.io.*; +import java.net.*; +import java.nio.file.*; +import java.security.SecureRandom; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.Consumer; +import static p.studio.app.runtime.studio.StudioWire.*; +import p.studio.app.runtime.studio.StudioWire.Reader; +import p.studio.app.runtime.studio.StudioWire.Writer; + +/** Owns a direct child runtime and two private loopback channels. */ +public final class StudioRuntimeGateway implements RuntimeGateway { + private final ObjectMapper mapper; + public StudioRuntimeGateway(ObjectMapper mapper){this.mapper=Objects.requireNonNull(mapper);} + @Override public boolean interactive(){return true;} + @Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,Consumer logs)throws Exception { + return start(project,setup,logs,PlayOptions.PERSISTENT); + } + @Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup, + Consumer logs,PlayOptions options)throws Exception { + new p.studio.app.assets.ManagedAssetGuard(mapper).require(project.rootPath(),project.rootPath().resolve("build"),setup); + Path executable=executable(setup); + List command=new ArrayList<>(List.of(executable.toString(),"--studio","--run",project.rootPath().resolve("build").toString())); + if(project.memcardSlots()!=null&&!options.disposableSave()){ + Path image=ProjectCartridgeConfiguration.selectedImage(project,setup); + if(!Files.isRegularFile(image))throw new IOException("Select an existing development save or an explicitly disposable session"); + command.add("--memcard");command.add(image.toString()); + } + InetAddress loopback=InetAddress.getByName("127.0.0.1"); + byte[] session=new byte[16],token=new byte[32];SecureRandom random=new SecureRandom();random.nextBytes(session);random.nextBytes(token); + Process process=null;Socket control=null,video=null; + ExecutorService io=Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("studio-play-io-",0).factory()); + try(ServerSocket controls=new ServerSocket(0,4,loopback);ServerSocket videos=new ServerSocket(0,4,loopback)){ + process=new ProcessBuilder(command).directory(project.rootPath().toFile()).start(); + CompletableFuture stdout=drain(process.getInputStream(),false,logs,io); + CompletableFuture stderr=drain(process.getErrorStream(),true,logs,io); + byte[] bootstrap=little(53).put(session).put(token).putShort((short)controls.getLocalPort()) + .putShort((short)videos.getLocalPort()).put((byte)(options.disposableSave()?1:0)).array(); + try(OutputStream input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,bootstrap);} + long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(10); + Accepted c=accept(controls,session,token,1,process,deadline);control=c.socket(); + Accepted v=accept(videos,session,token,2,process,deadline);video=v.socket(); + control.setSoTimeout(remaining(deadline)); + Message ready=c.reader().receive(); + if(ready.header().kind()!=READY||ready.header().request()!=0||ready.payload().length<16)throw new IOException("Interactive runtime did not become ready"); + var fields=java.nio.ByteBuffer.wrap(ready.payload()).order(java.nio.ByteOrder.LITTLE_ENDIAN); + int width=fields.getInt(),height=fields.getInt(),fps=fields.getInt(),format=fields.getInt(); + frameBytes(width,height,width); + if(fps!=60||format!=RGBA8)throw new IOException("Unsupported interactive display format"); + String version=text(ready.payload(),16); + logs.accept(RuntimeLogEntry.info("Studio Play protocol 1.0; runtime "+version)); + control.setSoTimeout(0);video.setSoTimeout(0); + var connection=new StudioRuntimeConnection(process,control,video,c.reader(),v.reader(),session,width,height,logs,io,stdout,stderr); + connection.completion().whenComplete((code,failure)->io.shutdown()); + return connection; + }catch(Throwable failure){ + close(control);close(video); + if(process!=null){process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();process.waitFor(2,TimeUnit.SECONDS);} + io.shutdownNow(); + throw failure; + }finally{Arrays.fill(token,(byte)0);} + } + private static Path executable(ProjectLocalStudioSetup setup)throws IOException { + if(setup.prometeuRuntimePath()==null)throw new IOException("Select a runtime installation"); + String name=System.getProperty("os.name").startsWith("Windows")?"prometeu-runtime.exe":"prometeu-runtime"; + Path path=Path.of(setup.prometeuRuntimePath()).resolve(name).toAbsolutePath().normalize(); + if(!Files.isRegularFile(path)||!Files.isExecutable(path))throw new IOException("Interactive runtime not found: "+path); + return path; + } + private record Accepted(Socket socket,Reader reader){ } + private static Accepted accept(ServerSocket listener,byte[] session,byte[] token,int role,Process process,long deadline)throws IOException { + listener.setSoTimeout(100); + while(System.nanoTime() drain(InputStream source,boolean error,Consumer logs,Executor executor){ + return CompletableFuture.runAsync(()->{ + try(var reader=new InputStreamReader(source,java.nio.charset.StandardCharsets.UTF_8)){ + StringBuilder line=new StringBuilder();boolean truncated=false;char[] chars=new char[2048];int count; + while((count=reader.read(chars))!=-1){for(int i=0;i BOOTSTRAP || sequence == 0 || length < 0 + || length > (kind == FRAME ? FRAME_LIMIT : CONTROL_LIMIT)) + throw new IllegalArgumentException("Invalid Studio message type, sequence or payload length"); + } + public byte[] encode() { + return little(HEADER_BYTES).putInt(0x31545350).putShort((short)1).putShort((short)0) + .putShort((short)kind).putShort((short)0).putInt(length).putLong(sequence).putLong(request).array(); + } + public static Header decode(byte[] bytes) throws IOException { + if (bytes.length != HEADER_BYTES) throw new IOException("Truncated Studio header"); + var b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); + if (b.getInt()!=0x31545350 || b.getShort()!=1 || b.getShort()!=0) + throw new IOException("Incompatible Studio protocol magic/version"); + int kind = Short.toUnsignedInt(b.getShort()); + if (b.getShort()!=0) throw new IOException("Unknown Studio protocol flags"); + long length = Integer.toUnsignedLong(b.getInt()), seq=b.getLong(), request=b.getLong(); + if (length > FRAME_LIMIT) throw new IOException("Studio payload exceeds limit"); + try { return new Header(kind, (int)length, seq, request); } + catch (IllegalArgumentException e) { throw new IOException(e.getMessage(),e); } + } + } + public record Message(Header header, byte[] payload) { } + public static final class Reader { + private final DataInputStream input; + private final byte[] header = new byte[HEADER_BYTES]; + private long sequence; + public Reader(InputStream input) { this.input = new DataInputStream(input); } + public Header nextHeader() throws IOException { + input.readFully(header); + Header result = Header.decode(header); + if (Long.compareUnsigned(result.sequence(),sequence) <= 0) + throw new IOException("Non-monotonic Studio sequence"); + sequence = result.sequence(); return result; + } + public void readFully(byte[] into, int offset, int length) throws IOException { input.readFully(into,offset,length); } + public Message receive() throws IOException { + Header h = nextHeader(); + if (h.kind()==FRAME) throw new IOException("Video must use the bounded frame pool"); + byte[] bytes = new byte[h.length()]; input.readFully(bytes); return new Message(h,bytes); + } + } + public static final class Writer { + private final OutputStream output; + private long sequence; + public Writer(OutputStream output) { this.output=output; } + public synchronized void send(int kind,long request,byte[] bytes) throws IOException { + if (++sequence==0) throw new IOException("Studio sequence exhausted"); + try { output.write(new Header(kind,bytes.length,sequence,request).encode()); } + catch (IllegalArgumentException e) { throw new IOException(e.getMessage(),e); } + output.write(bytes); output.flush(); + } + } + public static int frameBytes(int width,int height,int stride) throws IOException { + if (width <= 0 || height <= 0 || stride != width) throw new IOException("Invalid Studio frame dimensions/stride"); + final long bytes; + try { bytes = Math.multiplyExact(Math.multiplyExact((long)width,height),4); } + catch (ArithmeticException e) { throw new IOException("Studio frame dimensions overflow",e); } + if (bytes > FRAME_LIMIT-FRAME_METADATA_BYTES) throw new IOException("Studio frame exceeds limit"); + return (int)bytes; + } + public static String text(byte[] bytes,int offset) throws IOException { + try { return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes,offset,bytes.length-offset)).toString(); } + catch (CharacterCodingException e) { throw new IOException("Invalid Studio UTF-8",e); } + } +} diff --git a/prometeu-app/src/main/resources/asset-capacity/catalog.json b/prometeu-app/src/main/resources/asset-capacity/catalog.json index 292b3554..4b86f06d 100644 --- a/prometeu-app/src/main/resources/asset-capacity/catalog.json +++ b/prometeu-app/src/main/resources/asset-capacity/catalog.json @@ -33,6 +33,72 @@ "prometeu-headless": "18423f798ab28bbd38c12a7ee46459f3ef3d08876cc64327952f57be041fc5df", "prometeu-runtime": "ee00a587eb48030d1455d3c9bedd784ab620309a09877b50fe3641ae502635df" } + }, + { + "profile": { + "contractVersion": 1, + "profileId": "macos-arm64-studio-play-v1-b377b99e40b7", + "runtimeVersion": "0.1.0", + "executableSha256": "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a", + "limits": { + "glyph": 16, + "scene": 16 + }, + "evidence": [ + { + "bankType": "glyph", + "acceptedPreloads": 16, + "rejectedPreloads": 17, + "evidencePath": "asset-capacity/evidence/studio-play-native-capacity.json", + "evidenceSha256": "3890ff2fe308f3b6a57f71e30e5f10db13c73871aa09dc451bbcff148982ff5c" + }, + { + "bankType": "scene", + "acceptedPreloads": 16, + "rejectedPreloads": 17, + "evidencePath": "asset-capacity/evidence/studio-play-native-capacity.json", + "evidenceSha256": "3890ff2fe308f3b6a57f71e30e5f10db13c73871aa09dc451bbcff148982ff5c" + } + ] + }, + "executables": { + "prometeu": "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a", + "prometeu-headless": "3ace82881012fbdb83834055cf9f9fb759256da6d95260bce80de045f978ece5", + "prometeu-runtime": "b56341fd45011871ef192a7788eeef2fb15edb8b4fd4fbd03e2d03a378cfd8a0" + } + }, + { + "profile": { + "contractVersion": 1, + "profileId": "native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60", + "runtimeVersion": "0.1.0", + "executableSha256": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3", + "limits": { + "glyph": 16, + "scene": 16 + }, + "evidence": [ + { + "bankType": "glyph", + "acceptedPreloads": 16, + "rejectedPreloads": 17, + "evidencePath": "asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json", + "evidenceSha256": "89345c8a70973c5389c91ed02d1fe0866da30eaaa864d8602cb11c8ea25cdbc0" + }, + { + "bankType": "scene", + "acceptedPreloads": 16, + "rejectedPreloads": 17, + "evidencePath": "asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json", + "evidenceSha256": "89345c8a70973c5389c91ed02d1fe0866da30eaaa864d8602cb11c8ea25cdbc0" + } + ] + }, + "executables": { + "prometeu": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3", + "prometeu-headless": "a1662aaae81794a0f1eedfdbe386a52601ca133cf1634845d82c882fa130c942", + "prometeu-runtime": "918ff7a8eccf3e7263cbfb265a27fd2d015a317d5bb0dcb25a801a04a7c969f6" + } } ] } diff --git a/prometeu-app/src/main/resources/asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json b/prometeu-app/src/main/resources/asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json new file mode 100644 index 00000000..0ba520f7 --- /dev/null +++ b/prometeu-app/src/main/resources/asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json @@ -0,0 +1,1675 @@ +{ + "installation" : "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/dist-staging/stable/prometeu-cli-aarch64-apple-darwin", + "runtimeVersion" : "0.1.0", + "scope" : "Actual packaged native 16/17 qualification, glyph/scene only; no runtime writes/builds or larger guest budgets. Native rejection reports the existing aggregate preload BackendError, not a fabricated slot detail.", + "observations" : [ { + "bankType" : "glyph", + "preloads" : 16, + "plan" : { + "banks" : [ { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank0/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank1/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank10/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank11/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank12/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank13/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank14/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank15/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank2/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank3/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank4/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank5/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank6/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank7/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank8/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph16/assets/bank9/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 1, + "slot" : 0, + "bankType" : "GLYPH" + }, { + "assetId" : 2, + "slot" : 1, + "bankType" : "GLYPH" + }, { + "assetId" : 3, + "slot" : 2, + "bankType" : "GLYPH" + }, { + "assetId" : 4, + "slot" : 3, + "bankType" : "GLYPH" + }, { + "assetId" : 5, + "slot" : 4, + "bankType" : "GLYPH" + }, { + "assetId" : 6, + "slot" : 5, + "bankType" : "GLYPH" + }, { + "assetId" : 7, + "slot" : 6, + "bankType" : "GLYPH" + }, { + "assetId" : 8, + "slot" : 7, + "bankType" : "GLYPH" + }, { + "assetId" : 9, + "slot" : 8, + "bankType" : "GLYPH" + }, { + "assetId" : 10, + "slot" : 9, + "bankType" : "GLYPH" + }, { + "assetId" : 11, + "slot" : 10, + "bankType" : "GLYPH" + }, { + "assetId" : 12, + "slot" : 11, + "bankType" : "GLYPH" + }, { + "assetId" : 13, + "slot" : 12, + "bankType" : "GLYPH" + }, { + "assetId" : 14, + "slot" : 13, + "bankType" : "GLYPH" + }, { + "assetId" : 15, + "slot" : 14, + "bankType" : "GLYPH" + }, { + "assetId" : 16, + "slot" : 15, + "bankType" : "GLYPH" + } ], + "diagnostics" : [ ] + }, + "observation" : { + "sessionId" : "45ff3ce82f3d781fca775f7079f7cdda", + "buildId" : "qualify-glyph16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-19T10:46:31.400015Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:31.378666Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:31.378666Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:31.378666Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-19T10:46:31.400015Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-19T10:46:31.387949Z", + "source" : "advance" + } + }, + "context" : { + "runtimeCommand" : "get_state", + "runtimeRequestId" : "5fc10f74-97f3-405c-8c12-f405cfa8b0ab", + "advanceRequestId" : "3b83f382-87e7-412d-bf94-44381b28424c" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "outcome" : "SUCCEEDED", + "nativeObservation" : { + "sessionId" : "45ff3ce82f3d781fca775f7079f7cdda", + "buildId" : "qualify-glyph16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-19T10:46:31.400015Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:31.378666Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:31.378666Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:31.378666Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-19T10:46:31.400015Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-19T10:46:31.387949Z", + "source" : "advance" + } + }, + "context" : { + "runtimeCommand" : "get_state", + "runtimeRequestId" : "5fc10f74-97f3-405c-8c12-f405cfa8b0ab", + "advanceRequestId" : "3b83f382-87e7-412d-bf94-44381b28424c" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "accepted" + }, { + "bankType" : "glyph", + "preloads" : 17, + "plan" : { + "banks" : [ { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank0/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank1/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank10/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank11/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank12/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank13/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank14/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank15/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 17, + "reference" : "asset:id:17", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank16/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank2/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank3/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank4/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank5/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank6/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank7/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank8/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/glyph17/assets/bank9/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 1, + "slot" : 0, + "bankType" : "GLYPH" + }, { + "assetId" : 2, + "slot" : 1, + "bankType" : "GLYPH" + }, { + "assetId" : 3, + "slot" : 2, + "bankType" : "GLYPH" + }, { + "assetId" : 4, + "slot" : 3, + "bankType" : "GLYPH" + }, { + "assetId" : 5, + "slot" : 4, + "bankType" : "GLYPH" + }, { + "assetId" : 6, + "slot" : 5, + "bankType" : "GLYPH" + }, { + "assetId" : 7, + "slot" : 6, + "bankType" : "GLYPH" + }, { + "assetId" : 8, + "slot" : 7, + "bankType" : "GLYPH" + }, { + "assetId" : 9, + "slot" : 8, + "bankType" : "GLYPH" + }, { + "assetId" : 10, + "slot" : 9, + "bankType" : "GLYPH" + }, { + "assetId" : 11, + "slot" : 10, + "bankType" : "GLYPH" + }, { + "assetId" : 12, + "slot" : 11, + "bankType" : "GLYPH" + }, { + "assetId" : 13, + "slot" : 12, + "bankType" : "GLYPH" + }, { + "assetId" : 14, + "slot" : 13, + "bankType" : "GLYPH" + }, { + "assetId" : 15, + "slot" : 14, + "bankType" : "GLYPH" + }, { + "assetId" : 16, + "slot" : 15, + "bankType" : "GLYPH" + }, { + "assetId" : 17, + "slot" : 16, + "bankType" : "GLYPH" + } ], + "diagnostics" : [ ] + }, + "failure" : { + "code" : "INFRASTRUCTURE_FAILURE", + "message" : "Runtime boot_failed: boot failed: PVM Panic: Cartridge preload failed: BackendError", + "runtimeError" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "details" : { }, + "observation" : { + "sessionId" : "19afd467c11db22d04240ce0a47253f2", + "buildId" : "qualify-glyph17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-19T10:46:31.971586Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:31.968803Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:31.968803Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:31.968803Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-19T10:46:31.971586Z", + "source" : "boot" + } + }, + "context" : { + "runtimeCommand" : "boot", + "runtimeRequestId" : "a09c6af1-c390-4623-a74c-c027b99f7ada" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + } + }, + "nativeObservation" : { + "sessionId" : "19afd467c11db22d04240ce0a47253f2", + "buildId" : "qualify-glyph17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-19T10:46:31.971586Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:31.968803Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:31.968803Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:31.968803Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-19T10:46:31.971586Z", + "source" : "boot" + } + }, + "context" : { + "runtimeCommand" : "boot", + "runtimeRequestId" : "a09c6af1-c390-4623-a74c-c027b99f7ada" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "rejected" + }, { + "bankType" : "scene", + "preloads" : 16, + "plan" : { + "banks" : [ { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank0/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank1/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank10/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank11/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank12/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank13/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank14/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 17, + "reference" : "asset:id:17", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank15/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank2/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank3/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank4/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank5/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank6/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank7/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank8/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/bank9/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene16/assets/source/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 2, + "slot" : 0, + "bankType" : "SCENE" + }, { + "assetId" : 3, + "slot" : 1, + "bankType" : "SCENE" + }, { + "assetId" : 4, + "slot" : 2, + "bankType" : "SCENE" + }, { + "assetId" : 5, + "slot" : 3, + "bankType" : "SCENE" + }, { + "assetId" : 6, + "slot" : 4, + "bankType" : "SCENE" + }, { + "assetId" : 7, + "slot" : 5, + "bankType" : "SCENE" + }, { + "assetId" : 8, + "slot" : 6, + "bankType" : "SCENE" + }, { + "assetId" : 9, + "slot" : 7, + "bankType" : "SCENE" + }, { + "assetId" : 10, + "slot" : 8, + "bankType" : "SCENE" + }, { + "assetId" : 11, + "slot" : 9, + "bankType" : "SCENE" + }, { + "assetId" : 12, + "slot" : 10, + "bankType" : "SCENE" + }, { + "assetId" : 13, + "slot" : 11, + "bankType" : "SCENE" + }, { + "assetId" : 14, + "slot" : 12, + "bankType" : "SCENE" + }, { + "assetId" : 15, + "slot" : 13, + "bankType" : "SCENE" + }, { + "assetId" : 16, + "slot" : 14, + "bankType" : "SCENE" + }, { + "assetId" : 17, + "slot" : 15, + "bankType" : "SCENE" + } ], + "diagnostics" : [ ] + }, + "observation" : { + "sessionId" : "40199d22e96fbecf887ff92271c4fcad", + "buildId" : "qualify-scene16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-19T10:46:33.995408Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:33.984641Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:33.984641Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:33.984641Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-19T10:46:33.995408Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-19T10:46:33.991149Z", + "source" : "advance" + } + }, + "context" : { + "runtimeCommand" : "get_state", + "runtimeRequestId" : "088175c1-d819-45c5-b20b-7ac5755690f2", + "advanceRequestId" : "94477130-9ac1-42f6-a35e-97e2bacd2ced" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "outcome" : "SUCCEEDED", + "nativeObservation" : { + "sessionId" : "40199d22e96fbecf887ff92271c4fcad", + "buildId" : "qualify-scene16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-19T10:46:33.995408Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:33.984641Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:33.984641Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:33.984641Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-19T10:46:33.995408Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-19T10:46:33.991149Z", + "source" : "advance" + } + }, + "context" : { + "runtimeCommand" : "get_state", + "runtimeRequestId" : "088175c1-d819-45c5-b20b-7ac5755690f2", + "advanceRequestId" : "94477130-9ac1-42f6-a35e-97e2bacd2ced" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "accepted" + }, { + "bankType" : "scene", + "preloads" : 17, + "plan" : { + "banks" : [ { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank0/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank1/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank10/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank11/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank12/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank13/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank14/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 17, + "reference" : "asset:id:17", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank15/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 18, + "reference" : "asset:id:18", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank16/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank2/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank3/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank4/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank5/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank6/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank7/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank8/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/bank9/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-11638089540450628343/scene17/assets/source/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 2, + "slot" : 0, + "bankType" : "SCENE" + }, { + "assetId" : 3, + "slot" : 1, + "bankType" : "SCENE" + }, { + "assetId" : 4, + "slot" : 2, + "bankType" : "SCENE" + }, { + "assetId" : 5, + "slot" : 3, + "bankType" : "SCENE" + }, { + "assetId" : 6, + "slot" : 4, + "bankType" : "SCENE" + }, { + "assetId" : 7, + "slot" : 5, + "bankType" : "SCENE" + }, { + "assetId" : 8, + "slot" : 6, + "bankType" : "SCENE" + }, { + "assetId" : 9, + "slot" : 7, + "bankType" : "SCENE" + }, { + "assetId" : 10, + "slot" : 8, + "bankType" : "SCENE" + }, { + "assetId" : 11, + "slot" : 9, + "bankType" : "SCENE" + }, { + "assetId" : 12, + "slot" : 10, + "bankType" : "SCENE" + }, { + "assetId" : 13, + "slot" : 11, + "bankType" : "SCENE" + }, { + "assetId" : 14, + "slot" : 12, + "bankType" : "SCENE" + }, { + "assetId" : 15, + "slot" : 13, + "bankType" : "SCENE" + }, { + "assetId" : 16, + "slot" : 14, + "bankType" : "SCENE" + }, { + "assetId" : 17, + "slot" : 15, + "bankType" : "SCENE" + }, { + "assetId" : 18, + "slot" : 16, + "bankType" : "SCENE" + } ], + "diagnostics" : [ ] + }, + "failure" : { + "code" : "INFRASTRUCTURE_FAILURE", + "message" : "Runtime boot_failed: boot failed: PVM Panic: Cartridge preload failed: BackendError", + "runtimeError" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "details" : { }, + "observation" : { + "sessionId" : "28b948bb65713faa6b446260ea85054b", + "buildId" : "qualify-scene17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-19T10:46:38.183396Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:38.176083Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:38.176083Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:38.176083Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-19T10:46:38.183396Z", + "source" : "boot" + } + }, + "context" : { + "runtimeCommand" : "boot", + "runtimeRequestId" : "a799c778-0eca-4b93-bf96-5cc28bbbbd12" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + } + }, + "nativeObservation" : { + "sessionId" : "28b948bb65713faa6b446260ea85054b", + "buildId" : "qualify-scene17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-19T10:46:38.183396Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "runtimeVersion" : "0.1.0", + "limitsObservation" : { + "observedAt" : "2026-11-19T10:46:38.176083Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-19T10:46:38.176083Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-19T10:46:38.176083Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-19T10:46:38.183396Z", + "source" : "boot" + } + }, + "context" : { + "runtimeCommand" : "boot", + "runtimeRequestId" : "a799c778-0eca-4b93-bf96-5cc28bbbbd12" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "rejected" + } ], + "executables" : { + "prometeu" : "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3", + "prometeu-headless" : "a1662aaae81794a0f1eedfdbe386a52601ca133cf1634845d82c882fa130c942", + "prometeu-runtime" : "918ff7a8eccf3e7263cbfb265a27fd2d015a317d5bb0dcb25a801a04a7c969f6" + } +} \ No newline at end of file diff --git a/prometeu-app/src/main/resources/asset-capacity/evidence/studio-play-native-capacity.json b/prometeu-app/src/main/resources/asset-capacity/evidence/studio-play-native-capacity.json new file mode 100644 index 00000000..23a25293 --- /dev/null +++ b/prometeu-app/src/main/resources/asset-capacity/evidence/studio-play-native-capacity.json @@ -0,0 +1,1675 @@ +{ + "runtimeVersion" : "0.1.0", + "installation" : "/private/tmp/prometeu-wrk0014-runtime", + "executables" : { + "prometeu" : "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a", + "prometeu-headless" : "3ace82881012fbdb83834055cf9f9fb759256da6d95260bce80de045f978ece5", + "prometeu-runtime" : "b56341fd45011871ef192a7788eeef2fb15edb8b4fd4fbd03e2d03a378cfd8a0" + }, + "observations" : [ { + "bankType" : "glyph", + "preloads" : 16, + "plan" : { + "banks" : [ { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank0/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank1/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank10/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank11/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank12/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank13/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank14/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank15/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank2/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank3/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank4/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank5/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank6/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank7/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank8/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph16/assets/bank9/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 1, + "slot" : 0, + "bankType" : "GLYPH" + }, { + "assetId" : 2, + "slot" : 1, + "bankType" : "GLYPH" + }, { + "assetId" : 3, + "slot" : 2, + "bankType" : "GLYPH" + }, { + "assetId" : 4, + "slot" : 3, + "bankType" : "GLYPH" + }, { + "assetId" : 5, + "slot" : 4, + "bankType" : "GLYPH" + }, { + "assetId" : 6, + "slot" : 5, + "bankType" : "GLYPH" + }, { + "assetId" : 7, + "slot" : 6, + "bankType" : "GLYPH" + }, { + "assetId" : 8, + "slot" : 7, + "bankType" : "GLYPH" + }, { + "assetId" : 9, + "slot" : 8, + "bankType" : "GLYPH" + }, { + "assetId" : 10, + "slot" : 9, + "bankType" : "GLYPH" + }, { + "assetId" : 11, + "slot" : 10, + "bankType" : "GLYPH" + }, { + "assetId" : 12, + "slot" : 11, + "bankType" : "GLYPH" + }, { + "assetId" : 13, + "slot" : 12, + "bankType" : "GLYPH" + }, { + "assetId" : 14, + "slot" : 13, + "bankType" : "GLYPH" + }, { + "assetId" : 15, + "slot" : 14, + "bankType" : "GLYPH" + }, { + "assetId" : 16, + "slot" : 15, + "bankType" : "GLYPH" + } ], + "diagnostics" : [ ] + }, + "observation" : { + "sessionId" : "6ab247d0eb433e863392df5a153f2c5d", + "buildId" : "qualify-glyph16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-18T23:01:08.555341Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:08.478820Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:08.478820Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:08.478820Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-18T23:01:08.555341Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-18T23:01:08.514779Z", + "source" : "advance" + } + }, + "context" : { + "runtimeRequestId" : "837de1bd-0d2d-4227-9e9c-1a2c04d39f63", + "runtimeCommand" : "get_state", + "advanceRequestId" : "7d78cbbf-7d99-410b-af1a-ce576001684a" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "outcome" : "SUCCEEDED", + "nativeObservation" : { + "sessionId" : "6ab247d0eb433e863392df5a153f2c5d", + "buildId" : "qualify-glyph16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-18T23:01:08.555341Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:08.478820Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:08.478820Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:08.478820Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-18T23:01:08.555341Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-18T23:01:08.514779Z", + "source" : "advance" + } + }, + "context" : { + "runtimeRequestId" : "837de1bd-0d2d-4227-9e9c-1a2c04d39f63", + "runtimeCommand" : "get_state", + "advanceRequestId" : "7d78cbbf-7d99-410b-af1a-ce576001684a" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "accepted" + }, { + "bankType" : "glyph", + "preloads" : 17, + "plan" : { + "banks" : [ { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank0/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank1/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank10/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank11/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank12/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank13/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank14/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank15/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 17, + "reference" : "asset:id:17", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank16/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank2/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank3/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank4/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank5/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank6/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank7/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank8/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/glyph17/assets/bank9/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 1, + "slot" : 0, + "bankType" : "GLYPH" + }, { + "assetId" : 2, + "slot" : 1, + "bankType" : "GLYPH" + }, { + "assetId" : 3, + "slot" : 2, + "bankType" : "GLYPH" + }, { + "assetId" : 4, + "slot" : 3, + "bankType" : "GLYPH" + }, { + "assetId" : 5, + "slot" : 4, + "bankType" : "GLYPH" + }, { + "assetId" : 6, + "slot" : 5, + "bankType" : "GLYPH" + }, { + "assetId" : 7, + "slot" : 6, + "bankType" : "GLYPH" + }, { + "assetId" : 8, + "slot" : 7, + "bankType" : "GLYPH" + }, { + "assetId" : 9, + "slot" : 8, + "bankType" : "GLYPH" + }, { + "assetId" : 10, + "slot" : 9, + "bankType" : "GLYPH" + }, { + "assetId" : 11, + "slot" : 10, + "bankType" : "GLYPH" + }, { + "assetId" : 12, + "slot" : 11, + "bankType" : "GLYPH" + }, { + "assetId" : 13, + "slot" : 12, + "bankType" : "GLYPH" + }, { + "assetId" : 14, + "slot" : 13, + "bankType" : "GLYPH" + }, { + "assetId" : 15, + "slot" : 14, + "bankType" : "GLYPH" + }, { + "assetId" : 16, + "slot" : 15, + "bankType" : "GLYPH" + }, { + "assetId" : 17, + "slot" : 16, + "bankType" : "GLYPH" + } ], + "diagnostics" : [ ] + }, + "failure" : { + "code" : "INFRASTRUCTURE_FAILURE", + "message" : "Runtime boot_failed: boot failed: PVM Panic: Cartridge preload failed: BackendError", + "runtimeError" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "details" : { }, + "observation" : { + "sessionId" : "d500c4988dd5adb6f6d77d8316adda25", + "buildId" : "qualify-glyph17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-18T23:01:09.237187Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:09.232864Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:09.232864Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:09.232864Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-18T23:01:09.237187Z", + "source" : "boot" + } + }, + "context" : { + "runtimeRequestId" : "52eded6c-c195-4378-ad25-ef2d65d0a67d", + "runtimeCommand" : "boot" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + } + }, + "nativeObservation" : { + "sessionId" : "d500c4988dd5adb6f6d77d8316adda25", + "buildId" : "qualify-glyph17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-18T23:01:09.237187Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:09.232864Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:09.232864Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:09.232864Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-18T23:01:09.237187Z", + "source" : "boot" + } + }, + "context" : { + "runtimeRequestId" : "52eded6c-c195-4378-ad25-ef2d65d0a67d", + "runtimeCommand" : "boot" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "rejected" + }, { + "bankType" : "scene", + "preloads" : 16, + "plan" : { + "banks" : [ { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank0/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank1/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank10/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank11/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank12/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank13/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank14/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 17, + "reference" : "asset:id:17", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank15/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank2/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank3/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank4/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank5/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank6/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank7/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank8/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/bank9/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene16/assets/source/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 2, + "slot" : 0, + "bankType" : "SCENE" + }, { + "assetId" : 3, + "slot" : 1, + "bankType" : "SCENE" + }, { + "assetId" : 4, + "slot" : 2, + "bankType" : "SCENE" + }, { + "assetId" : 5, + "slot" : 3, + "bankType" : "SCENE" + }, { + "assetId" : 6, + "slot" : 4, + "bankType" : "SCENE" + }, { + "assetId" : 7, + "slot" : 5, + "bankType" : "SCENE" + }, { + "assetId" : 8, + "slot" : 6, + "bankType" : "SCENE" + }, { + "assetId" : 9, + "slot" : 7, + "bankType" : "SCENE" + }, { + "assetId" : 10, + "slot" : 8, + "bankType" : "SCENE" + }, { + "assetId" : 11, + "slot" : 9, + "bankType" : "SCENE" + }, { + "assetId" : 12, + "slot" : 10, + "bankType" : "SCENE" + }, { + "assetId" : 13, + "slot" : 11, + "bankType" : "SCENE" + }, { + "assetId" : 14, + "slot" : 12, + "bankType" : "SCENE" + }, { + "assetId" : 15, + "slot" : 13, + "bankType" : "SCENE" + }, { + "assetId" : 16, + "slot" : 14, + "bankType" : "SCENE" + }, { + "assetId" : 17, + "slot" : 15, + "bankType" : "SCENE" + } ], + "diagnostics" : [ ] + }, + "observation" : { + "sessionId" : "e60f8aad3646adcf63a1225a10ce2b4b", + "buildId" : "qualify-scene16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-18T23:01:10.216528Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:10.195436Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:10.195436Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:10.195436Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-18T23:01:10.216528Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-18T23:01:10.202376Z", + "source" : "advance" + } + }, + "context" : { + "runtimeRequestId" : "5eb785db-3099-46c6-a722-59780aeb2118", + "runtimeCommand" : "get_state", + "advanceRequestId" : "10d40c81-61d0-4c17-b26f-7f72f1b5f9cd" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "outcome" : "SUCCEEDED", + "nativeObservation" : { + "sessionId" : "e60f8aad3646adcf63a1225a10ce2b4b", + "buildId" : "qualify-scene16", + "lifecycle" : "GUEST_OBSERVED", + "source" : "get_state", + "observedAt" : "2026-11-18T23:01:10.216528Z", + "progress" : { + "requestedFrames" : 1, + "completedFrames" : 1 + }, + "lastFrame" : { + "logicalFrameIndex" : 1, + "frameId" : 0 + }, + "captureStale" : false, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:10.195436Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:10.195436Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:10.195436Z", + "source" : "initialize" + }, + "state" : { + "appId" : 27301, + "logicalFrameIndex" : 1, + "pc" : 36, + "stackTop" : [ ], + "status" : "paused", + "tickIndex" : 1 + }, + "stateObservation" : { + "observedAt" : "2026-11-18T23:01:10.216528Z", + "source" : "get_state" + }, + "advance" : { + "completed" : 1, + "requested" : 1, + "stop" : "completed" + }, + "advanceObservation" : { + "observedAt" : "2026-11-18T23:01:10.202376Z", + "source" : "advance" + } + }, + "context" : { + "runtimeRequestId" : "5eb785db-3099-46c6-a722-59780aeb2118", + "runtimeCommand" : "get_state", + "advanceRequestId" : "10d40c81-61d0-4c17-b26f-7f72f1b5f9cd" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "accepted" + }, { + "bankType" : "scene", + "preloads" : 17, + "plan" : { + "banks" : [ { + "assetId" : 2, + "reference" : "asset:id:2", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank0/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 3, + "reference" : "asset:id:3", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank1/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 12, + "reference" : "asset:id:12", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank10/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 13, + "reference" : "asset:id:13", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank11/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 14, + "reference" : "asset:id:14", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank12/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 15, + "reference" : "asset:id:15", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank13/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 16, + "reference" : "asset:id:16", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank14/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 17, + "reference" : "asset:id:17", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank15/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 18, + "reference" : "asset:id:18", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank16/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 4, + "reference" : "asset:id:4", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank2/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 5, + "reference" : "asset:id:5", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank3/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 6, + "reference" : "asset:id:6", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank4/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 7, + "reference" : "asset:id:7", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank5/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 8, + "reference" : "asset:id:8", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank6/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 9, + "reference" : "asset:id:9", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank7/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 10, + "reference" : "asset:id:10", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank8/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 11, + "reference" : "asset:id:11", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/bank9/", + "bankType" : "SCENE", + "buildSelected" : true, + "included" : true, + "contentCount" : 0, + "metadata" : { }, + "coldDependencies" : [ ] + }, { + "assetId" : 1, + "reference" : "asset:id:1", + "root" : "file:///private/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/junit-7925975554970522147/scene17/assets/source/", + "bankType" : "GLYPH", + "buildSelected" : true, + "included" : true, + "contentCount" : 1, + "metadata" : { + "tile_size" : "16x16" + }, + "coldDependencies" : [ ] + } ], + "preload" : [ { + "assetId" : 2, + "slot" : 0, + "bankType" : "SCENE" + }, { + "assetId" : 3, + "slot" : 1, + "bankType" : "SCENE" + }, { + "assetId" : 4, + "slot" : 2, + "bankType" : "SCENE" + }, { + "assetId" : 5, + "slot" : 3, + "bankType" : "SCENE" + }, { + "assetId" : 6, + "slot" : 4, + "bankType" : "SCENE" + }, { + "assetId" : 7, + "slot" : 5, + "bankType" : "SCENE" + }, { + "assetId" : 8, + "slot" : 6, + "bankType" : "SCENE" + }, { + "assetId" : 9, + "slot" : 7, + "bankType" : "SCENE" + }, { + "assetId" : 10, + "slot" : 8, + "bankType" : "SCENE" + }, { + "assetId" : 11, + "slot" : 9, + "bankType" : "SCENE" + }, { + "assetId" : 12, + "slot" : 10, + "bankType" : "SCENE" + }, { + "assetId" : 13, + "slot" : 11, + "bankType" : "SCENE" + }, { + "assetId" : 14, + "slot" : 12, + "bankType" : "SCENE" + }, { + "assetId" : 15, + "slot" : 13, + "bankType" : "SCENE" + }, { + "assetId" : 16, + "slot" : 14, + "bankType" : "SCENE" + }, { + "assetId" : 17, + "slot" : 15, + "bankType" : "SCENE" + }, { + "assetId" : 18, + "slot" : 16, + "bankType" : "SCENE" + } ], + "diagnostics" : [ ] + }, + "failure" : { + "code" : "INFRASTRUCTURE_FAILURE", + "message" : "Runtime boot_failed: boot failed: PVM Panic: Cartridge preload failed: BackendError", + "runtimeError" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "details" : { }, + "observation" : { + "sessionId" : "54dbcd1273acd30da4104aba4ec77381", + "buildId" : "qualify-scene17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-18T23:01:11.068887Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:11.066818Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:11.066818Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:11.066818Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-18T23:01:11.068887Z", + "source" : "boot" + } + }, + "context" : { + "runtimeRequestId" : "f9d29786-7311-4358-bd78-eb8e7a6dc500", + "runtimeCommand" : "boot" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + } + }, + "nativeObservation" : { + "sessionId" : "54dbcd1273acd30da4104aba4ec77381", + "buildId" : "qualify-scene17", + "lifecycle" : "UNKNOWN", + "source" : "boot", + "observedAt" : "2026-11-18T23:01:11.068887Z", + "progress" : { + "requestedFrames" : null, + "completedFrames" : null + }, + "lastFrame" : null, + "captureStale" : true, + "nativeDetails" : { + "limits" : { + "callTimeoutMs" : 60000, + "handshakeTimeoutMs" : 5000, + "maxCommandBytes" : 65536, + "maxFrames" : 600, + "maxResponseBytes" : 33554432, + "shutdownTimeoutMs" : 5000 + }, + "runtimeVersion" : "0.1.0", + "capabilities" : [ "boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "log_read", "cancel", "shutdown", "memcard", "memcard_mount", "memcard_unmount", "get_memcard_state", "memcard_reconcile", "memcard_continue_in_memory" ], + "limitsObservation" : { + "observedAt" : "2026-11-18T23:01:11.066818Z", + "source" : "initialize" + }, + "runtimeVersionObservation" : { + "observedAt" : "2026-11-18T23:01:11.066818Z", + "source" : "initialize" + }, + "capabilitiesObservation" : { + "observedAt" : "2026-11-18T23:01:11.066818Z", + "source" : "initialize" + }, + "error" : { + "code" : "boot_failed", + "details" : { + "fault" : { + "kind" : "vm_panic", + "message" : "Cartridge preload failed: BackendError", + "pc" : null, + "summary" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "reason" : "PVM Panic: Cartridge preload failed: BackendError" + }, + "message" : "boot failed: PVM Panic: Cartridge preload failed: BackendError" + }, + "errorObservation" : { + "observedAt" : "2026-11-18T23:01:11.068887Z", + "source" : "boot" + } + }, + "context" : { + "runtimeRequestId" : "f9d29786-7311-4358-bd78-eb8e7a6dc500", + "runtimeCommand" : "boot" + }, + "unavailable" : [ ], + "recovery" : [ { + "action" : "inspect_state", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + }, { + "action" : "inspect_fault", + "preconditions" : [ "session process is available and no conflicting operation is active" ], + "automatic" : false + } ] + }, + "expected" : "rejected" + } ], + "scope" : "Actual packaged native 16/17 qualification, glyph/scene only; no runtime writes/builds or larger guest budgets. Native rejection reports the existing aggregate preload BackendError, not a fabricated slot detail." +} \ No newline at end of file diff --git a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java index 302ba15e..16a9f275 100644 --- a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java @@ -26,6 +26,7 @@ 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. */ +@org.junit.jupiter.api.Tag("integration") class DevDesktopTest { @TempDir Path root; @BeforeAll static void toolkit() throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java index b510f311..24e7432e 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -13,6 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +@org.junit.jupiter.api.Tag("integration") class StudioApplicationConfigurationTest { @Test void bootsAndClosesWithoutAWebApplicationContext() { diff --git a/prometeu-app/src/test/java/p/studio/app/StudioPlayDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/StudioPlayDesktopTest.java new file mode 100644 index 00000000..97d1d22f --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/StudioPlayDesktopTest.java @@ -0,0 +1,235 @@ +package p.studio.app; + +import com.fasterxml.jackson.databind.ObjectMapper; +import javafx.application.Platform; +import javafx.scene.control.*; +import javafx.scene.image.ImageView; +import javafx.scene.input.*; +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 p.studio.api.execution.*; +import p.studio.api.project.*; +import p.studio.api.session.ProjectSessionFactory; +import p.studio.core.project.*; +import p.studio.core.execution.DefaultExecutionControllerFactory; +import p.studio.app.runtime.studio.StudioRuntimeGateway; +import p.studio.ui.javafx2.window.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Actual new frontend, real compiler/packer and direct installed native process. */ +@org.junit.jupiter.api.Tag("integration") +class StudioPlayDesktopTest { + @TempDir Path temporary; + static T fx(Callable action)throws Exception{ + var future=new CompletableFuture();Platform.runLater(()->{try{future.complete(action.call());}catch(Throwable f){future.completeExceptionally(f);}}); + return future.get(15,TimeUnit.SECONDS); + } + @BeforeAll static void toolkit()throws Exception{ + var ready=new CompletableFuture();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS); + } + @AfterAll static void stopToolkit(){Platform.exit();} + private static void await(BooleanSupplier condition,Supplier failure)throws Exception{ + long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(20); + while(System.nanoTime()>(); + var nativeGateway=new StudioRuntimeGateway(app.getBean(ObjectMapper.class)); + p.studio.core.runtime.RuntimeGateway gateway=new p.studio.core.runtime.RuntimeGateway(){ + public boolean interactive(){return true;} + public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer logs)throws Exception{return start(p,s,logs,PlayOptions.PERSISTENT);} + public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer logs,PlayOptions options)throws Exception{ + var actual=nativeGateway.start(p,s,logs,options); + return new p.studio.core.runtime.RuntimeConnection(){ + public CompletableFuture completion(){return actual.completion();} + public CompletableFuture startExecution(){return actual.startExecution();} + public CompletableFuture pause(){ + if(!delayedPause.getAndSet(false))return actual.pause(); + var result=new CompletableFuture();oldPause.set(result);return actual.pause().thenCompose(v->result); + } + public CompletableFuture resume(){return actual.resume();} + public CompletableFuture stopAsync(){return actual.stopAsync();} + public ExecutionFrame acquireLatestFrame(){return actual.acquireLatestFrame();} + public void input(ExecutionInput value){actual.input(value);} + public void close(){actual.close();} + }; + } + }; + var factory=new DefaultExecutionControllerFactory(app.getBean(p.studio.api.shipper.Shipper.class), + gateway,app.getBean(p.studio.api.operation.OperationExecutor.class),access); + var known=new KnownProjects(){public List listKnownProjects(){return List.of(ref);}public void remember(ProjectReference r){}public void forget(ProjectReference r){}}; + Stage stage=fx(Stage::new); + var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,app.getBean(ProjectSessionFactory.class),factory, + (project,setup)->{try(var lease=access.enterManual(project.rootPath())){setups.save(project,setup);}},executor,resources)); + try{ + fx(()->{window.showLauncher();stage.toFront();stage.requestFocus();assertNotNull(stage.getScene().lookup("#studio-shell"));window.openProject(root);return null;}); + await(()->{try{return fx(()->window.projectSession()!=null);}catch(Exception e){throw new RuntimeException(e);}},()->"Project did not open"); + Supplier facts=()->{try{capture(stage,"failure.png");return fx(()->"state="+window.projectSession().executionSession().snapshot().state()+" focused="+stage.isFocused()+" frames="+window.viewport().paintedFrames()+"\n"+((Label)stage.getScene().lookup("#studio-notice")).getText()+"\n"+((TextArea)stage.getScene().lookup("#execution-logs")).getText());}catch(Exception e){return e.toString();}}; + focus(stage); + fire(stage,"play");running(window,stage,facts); + await(()->{try{return fx(()->window.viewport().paintedFrames()>3);}catch(Exception e){throw new RuntimeException(e);}},facts); + fx(()->{assertTrue(stage.getScene().lookup("#runtime-path").isDisabled());return null;}); + assertThrows(p.studio.api.automation.ControlDeniedException.class,()->access.enterManual(root)); + fx(()->{ComboBox zoom=(ComboBox)stage.getScene().lookup("#viewport-zoom");zoom.setValue(4); + var image=(ImageView)stage.getScene().lookup("#game-image");assertEquals(1920,image.getFitWidth());assertFalse(image.isSmooth()); + zoom.setValue(2);assertEquals(960,image.getFitWidth());zoom.setValue(1);assertEquals(480,image.getFitWidth());return null;}); + // Deliver a real key edge through the viewport; Pong leaves its static menu. + // Zoom popup/native activation can transfer desktop focus. Establish the + // input precondition explicitly; the later focus-loss checks never resume. + running(window,stage,facts); + long before=imageHash(stage); + fx(()->{assertTrue(stage.isFocused(),"Keyboard qualification requires actual foreground focus"); + assertEquals(ExecutionState.RUNNING,window.projectSession().executionSession().snapshot().state()); + var surface=stage.getScene().lookup("#game-surface");surface.requestFocus(); + surface.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"a","a",KeyCode.A,false,false,false,false));return null;}); + try { + await(()->{try{return imageHash(stage)!=before;}catch(Exception e){throw new RuntimeException(e);}}, + ()->"Keyboard A must move Pong out of its menu\n"+facts.get()); + } finally { + fx(()->{stage.getScene().lookup("#game-surface").fireEvent(new KeyEvent(KeyEvent.KEY_RELEASED,"a","a",KeyCode.A,false,false,false,false));return null;}); + } + fire(stage,"pause");state(window,ExecutionState.PAUSED,facts); + long paused=fx(()->window.viewport().lastFrameId());Thread.sleep(200); + assertEquals(paused,fx(()->window.viewport().lastFrameId()));fire(stage,"resume");running(window,stage,facts); + // A window owned by Studio is not an application switch. + Stage owned=fx(()->{var s=new Stage();s.initOwner(stage);s.setScene(new javafx.scene.Scene(new Label("Studio dialog"),240,120));s.show();s.requestFocus();return s;});Thread.sleep(250); + assertEquals(ExecutionState.RUNNING,fx(()->window.projectSession().executionSession().snapshot().state())); + fx(()->{owned.hide();stage.requestFocus();stage.setIconified(true);return null;});state(window,ExecutionState.PAUSED,facts); + fx(()->{stage.setIconified(false);stage.requestFocus();return null;});Thread.sleep(200); + assertEquals(ExecutionState.PAUSED,fx(()->window.projectSession().executionSession().snapshot().state()));fire(stage,"resume");running(window,stage,facts); + Stage other=fx(()->{var s=new Stage();s.setTitle("Other application focus probe");s.setScene(new javafx.scene.Scene(new Label("Focus probe"),300,150));s.show();s.requestFocus();return s;});state(window,ExecutionState.PAUSED,facts); + fx(()->{other.hide();stage.requestFocus();return null;});Thread.sleep(200); + assertEquals(ExecutionState.PAUSED,fx(()->window.projectSession().executionSession().snapshot().state()));fire(stage,"resume");running(window,stage,facts); + capture(stage,"play.png"); + if(Boolean.getBoolean("studio.test.playStress")){ + var process=runtime();long runtimeCpu=cpuNanos(process); + long javaCpu=cpuNanos(ProcessHandle.current()); + long painted=fx(()->window.viewport().paintedFrames()); + long heapBefore=java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + Thread.sleep(30_000); + double p95=fx(()->window.viewport().latencyP95Millis());System.out.println("RECEIVE_TO_PAINT_P95_MS="+p95);assertTrue(p95<=33.4,"Idle receive-to-paint p95 "+p95); + System.out.println("PAINT_FPS="+(fx(()->window.viewport().paintedFrames())-painted)/30.0); + System.out.println("RUNTIME_CPU_SECONDS="+(cpuNanos(process)-runtimeCpu)/1e9); + System.out.println("JAVA_CPU_SECONDS="+(cpuNanos(ProcessHandle.current())-javaCpu)/1e9); + System.out.println("HEAP_USED_BEFORE_AFTER="+heapBefore+","+java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()); + assertEquals(ExecutionState.RUNNING,fx(()->window.projectSession().executionSession().snapshot().state()),facts); + assertTrue(fx(stage::isFocused),"Idle-host measurement requires the Studio to retain actual focus"); + long frame=fx(()->window.viewport().lastFrameId()); + fx(()->{Thread.sleep(500);return null;});Thread.sleep(70); + long afterFreeze=fx(()->window.viewport().lastFrameId()); + System.out.println("FX_FREEZE_FRAME_IDS="+frame+","+afterFreeze); + assertTrue(afterFreeze>frame+15,()->"Runtime must advance while FX is blocked: "+frame+" -> "+afterFreeze+"\n"+facts.get()); + for(int i=0;i<20;i++){fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);Thread.sleep(130); + assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads()); + fire(stage,"play");running(window,stage,facts);Thread.sleep(50); + assertEquals(1,runtimeCount());assertEquals(1,heartbeatThreads());} + System.out.println("PLAY_STOP_CYCLES=20"); + } + fire(stage,"stop");state(window,ExecutionState.STOPPED,facts); + await(()->{try{return fx(()->!stage.getScene().lookup("#runtime-path").isDisabled());}catch(Exception e){throw new RuntimeException(e);}},facts); + try(var lease=access.enterManual(root)){} + assertFalse(Files.exists(root.resolve(".codex")),"Play must not prepare an AI client"); + assertFalse(Files.exists(root.resolve("build.pmc"))); + fire(stage,"play");running(window,stage,facts); + delayedPause.set(true);fire(stage,"pause"); + await(()->oldPause.get()!=null,facts); + fire(stage,"stop");state(window,ExecutionState.STOPPED,facts); + fire(stage,"play");running(window,stage,facts); + oldPause.get().completeExceptionally(new java.io.IOException("obsolete-pause-result")); + Thread.sleep(200); + assertFalse(fx(()->((Label)stage.getScene().lookup("#studio-notice")).getText().contains("obsolete-pause-result")), + "An old command must not replace a new execution's feedback"); + runtime().destroyForcibly();state(window,ExecutionState.RUNTIME_FAILED,facts); + await(()->{try{return fx(()->!stage.getScene().lookup("#runtime-path").isDisabled());}catch(Exception e){throw new RuntimeException(e);}},facts); + assertTrue(fx(()->((TextArea)stage.getScene().lookup("#execution-logs")).getText().contains("Runtime"))); + fire(stage,"play");running(window,stage,facts); + fx(()->{window.requestCloseProject();return null;}); + await(()->{try{return fx(()->window.projectSession()==null);}catch(Exception e){throw new RuntimeException(e);}},facts); + fx(()->{assertNotNull(stage.getScene().lookup("#open-project"));return null;});capture(stage,"projects.png"); + assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads()); + }finally{fx(()->{window.close();stage.hide();return null;});} + } + } + static void fire(Stage stage,String id)throws Exception{fx(()->{Button button=(Button)stage.getScene().lookup("#"+id);assertFalse(button.isDisabled(),id+" disabled");button.fire();return null;});} + static void state(StudioWindowCoordinator2 w,ExecutionState expected,Supplier facts)throws Exception{ + await(()->{try{return fx(()->w.projectSession().executionSession().snapshot().state()==expected);}catch(Exception e){throw new RuntimeException(e);}},facts); + Thread.sleep(130); + } + static void running(StudioWindowCoordinator2 w,Stage stage,Supplier facts)throws Exception{ + focus(stage); + await(()->{try{return fx(()->{var state=w.projectSession().executionSession().snapshot().state(); + if(state==ExecutionState.PAUSED){stage.requestFocus();((Button)stage.getScene().lookup("#resume")).fire();} + return state==ExecutionState.RUNNING && stage.isFocused();});}catch(Exception e){throw new RuntimeException(e);}},facts);Thread.sleep(150); + } + static void focus(Stage stage)throws Exception{fx(()->{stage.setIconified(false);stage.toFront();stage.requestFocus(); + var point=stage.getScene().getRoot().localToScreen(10,10); + var robot=new javafx.scene.robot.Robot();robot.mouseMove(point);robot.mouseClick(MouseButton.PRIMARY);return null;});Thread.sleep(150);} + static void capture(Stage stage,String name)throws Exception{fx(()->{ + var image=stage.getScene().snapshot(null);var output=new java.awt.image.BufferedImage((int)image.getWidth(),(int)image.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB); + for(int y=0;y{var image=((ImageView)stage.getScene().lookup("#game-image")).getImage();long hash=1; + for(int y=0;y<(int)image.getHeight();y++)for(int x=0;x<(int)image.getWidth();x++)hash=31*hash+image.getPixelReader().getArgb(x,y);return hash;});} + static long runtimeCount(){return ProcessHandle.current().children().filter(p->p.isAlive()&&p.info().command().orElse("").endsWith("/prometeu-runtime")).count();} + static ProcessHandle runtime(){return ProcessHandle.current().children().filter(p->p.isAlive()&&p.info().command().orElse("").endsWith("/prometeu-runtime")).findFirst().orElseThrow();} + static long heartbeatThreads(){return Thread.getAllStackTraces().keySet().stream().filter(t->t.isAlive()&&t.getName().equals("studio-play-heartbeat")).count();} + static long cpuNanos(ProcessHandle process)throws Exception{ + var cpu=process.info().totalCpuDuration();if(cpu.isPresent())return cpu.get().toNanos(); + // HotSpot on this macOS does not expose child CPU duration through ProcessHandle.Info. + var query=new ProcessBuilder("/bin/ps","-p",Long.toString(process.pid()),"-o","cputime=").start(); + String value=new String(query.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8).trim(); + assertTrue(query.waitFor(2,TimeUnit.SECONDS));assertEquals(0,query.exitValue()); + double seconds=0;for(String component:value.split(":"))seconds=seconds*60+Double.parseDouble(component); + return (long)(seconds*1e9); + } + + @Test void viewportCopiesStablePixelsAndInvertsZoomWithoutClampingOutsideTouches()throws Exception{ + var input=new java.util.concurrent.atomic.AtomicReference<>(ExecutionInput.NEUTRAL); + byte[] pixels=new byte[4*2*4];for(int i=0;i(new ExecutionFrame(4,2,1,1,pixels,()->{})); + ExecutionController controller=new ExecutionController(){ + public p.studio.api.operation.OperationHandle play(){throw new UnsupportedOperationException();} + public void stop(){}public void close(){}public ExecutionFrame acquireLatestFrame(){return frame.getAndSet(null);} + public void input(ExecutionInput value){input.set(value);} + }; + var viewport=fx(()->new p.studio.ui.javafx2.play.PlaybackViewport(()->controller,()->ExecutionState.RUNNING)); + Stage stage=fx(()->{var s=new Stage();s.setScene(new javafx.scene.Scene(viewport,500,300));s.show();return s;}); + try{ + await(()->{try{return fx(()->viewport.paintedFrames()==1);}catch(Exception e){throw new RuntimeException(e);}},()->"Frame was not painted"); + fx(()->{viewport.zoom(4);stage.getScene().getRoot().applyCss();stage.getScene().getRoot().layout(); + ImageView image=(ImageView)stage.getScene().lookup("#game-image");assertEquals(0xffff0000,image.getImage().getPixelReader().getArgb(1,1)); + assertEquals(16,image.getFitWidth()); + pointer(image,MouseEvent.MOUSE_PRESSED,6,6);assertEquals(new ExecutionInput(4096,1,1),input.get()); + pointer(image,MouseEvent.MOUSE_DRAGGED,-1,6);assertEquals(0,input.get().buttons());assertEquals(-1,input.get().touchX()); + pointer(image,MouseEvent.MOUSE_PRESSED,14,6);assertEquals(new ExecutionInput(4096,3,1),input.get()); + pointer(image,MouseEvent.MOUSE_RELEASED,30,30);assertEquals(0,input.get().buttons()); + var surface=stage.getScene().lookup("#game-surface"); + surface.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"a","a",KeyCode.A,false,false,false,false));assertEquals(16,input.get().buttons()); + viewport.neutralize();assertEquals(0,input.get().buttons());return null;}); + }finally{fx(()->{viewport.close();stage.hide();return null;});} + } + static void pointer(ImageView image,javafx.event.EventType type,double x,double y){ + var point=image.localToScene(x,y); + image.fireEvent(new MouseEvent(type,point.getX(),point.getY(),0,0,MouseButton.PRIMARY,1, + false,false,false,false,type!=MouseEvent.MOUSE_RELEASED,false,false,false,false,false, + new PickResult(image,point.getX(),point.getY()))); + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java index c5cf0026..ab3a5b54 100644 --- a/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java @@ -15,6 +15,7 @@ import java.util.function.*; import static org.junit.jupiter.api.Assertions.*; /** Actual JavaFX editing, shared save/preview, drift repair and handoff lifecycle. */ +@org.junit.jupiter.api.Tag("integration") class AnimationDesktopTest { @TempDir Path root; @BeforeAll static void toolkit()throws Exception{ diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java index 2ab1cb92..1fd8a608 100644 --- a/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java @@ -16,6 +16,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** Production packaged runtime: canonical authoring -> generated PBS -> Composer -> pixels. */ +@org.junit.jupiter.api.Tag("integration") class AnimationInstalledRuntimeTest { @TempDir Path root; @Test void composedFramesMatchSharedPreviewAtEveryBoundary()throws Exception{ diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java index bcd3b9f4..8eeb4bbb 100644 --- a/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java @@ -24,6 +24,7 @@ import javax.imageio.ImageIO; import static org.junit.jupiter.api.Assertions.*; import static p.animation.AnimationDocument.*; +@org.junit.jupiter.api.Tag("integration") class AnimationIntegrationTest { @TempDir Path root; final ObjectMapper mapper=new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AssetAuthoringDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AssetAuthoringDesktopTest.java index f788d3f1..2fe90667 100644 --- a/prometeu-app/src/test/java/p/studio/app/animation/AssetAuthoringDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/animation/AssetAuthoringDesktopTest.java @@ -28,6 +28,7 @@ import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.*; /** Actual Assets controls, shared preview/publication, capacity projection and grant inspection. */ +@org.junit.jupiter.api.Tag("integration") class AssetAuthoringDesktopTest { @TempDir Path root; @BeforeAll static void toolkit()throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AssetBatchIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AssetBatchIntegrationTest.java index c92263d2..09a0e50e 100644 --- a/prometeu-app/src/test/java/p/studio/app/animation/AssetBatchIntegrationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/animation/AssetBatchIntegrationTest.java @@ -16,6 +16,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** Real packer/filesystem composition behind the same human/task service. */ +@org.junit.jupiter.api.Tag("integration") class AssetBatchIntegrationTest { @TempDir Path root; AnimationIntegrationTest fixture;FileAssetBatchWorkspace disk;AssetAuthoringService service; diff --git a/prometeu-app/src/test/java/p/studio/app/assets/AssetCapacityProfilesTest.java b/prometeu-app/src/test/java/p/studio/app/assets/AssetCapacityProfilesTest.java new file mode 100644 index 00000000..67195ec3 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/assets/AssetCapacityProfilesTest.java @@ -0,0 +1,93 @@ +package p.studio.app.assets; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.assets.AssetBudgets.*; +import p.studio.api.project.ProjectLocalStudioSetup; + +import java.io.ByteArrayInputStream; +import java.nio.file.*; +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; + +class AssetCapacityProfilesTest { + @TempDir Path installation; + private final ObjectMapper json = new ObjectMapper(); + private final byte[] evidence = "native qualification evidence".getBytes(java.nio.charset.StandardCharsets.UTF_8); + + @Test void findsCompleteBundleAfterAnOlderProfileWithTheSameDispatcher() throws Exception { + var old = bundle("old", "old-headless", "old-runtime"); + var current = bundle("current", "new-headless", "new-runtime"); + install("new-headless", "new-runtime"); + for (var order : List.of(List.of(old, current), List.of(current, old))) { + var selection = select(order, evidence); + assertEquals(QualificationState.known, selection.state(), selection.reason()); + assertEquals("current", selection.profile().profileId()); + } + } + + @Test void rejectsComponentsStitchedFromDifferentQualifiedBundles() throws Exception { + install("old-headless", "new-runtime"); + var selection = select(List.of(bundle("old", "old-headless", "old-runtime"), + bundle("new", "new-headless", "new-runtime")), evidence); + assertEquals(QualificationState.unknown, selection.state()); + assertNull(selection.profile()); + assertTrue(selection.reason().contains("component changed"), selection.reason()); + } + + @Test void rejectsChangedComponentAndCorruptOrMissingEvidence() throws Exception { + var current = bundle("current", "new-headless", "new-runtime"); + install("modified-headless", "new-runtime"); + assertEquals(QualificationState.unknown, select(List.of(current), evidence).state()); + install("new-headless", "new-runtime"); + for (byte[] resource : Arrays.asList("corrupt".getBytes(), null)) { + var selection = select(List.of(current), resource); + assertEquals(QualificationState.unknown, selection.state()); + assertTrue(selection.reason().contains("evidence integrity"), selection.reason()); + } + } + + @Test void rejectsUnqualifiedDispatcherAndIncompleteIdentity() throws Exception { + var current = bundle("current", "new-headless", "new-runtime"); + install("new-headless", "new-runtime"); + Files.writeString(installation.resolve(executable("prometeu")), "unqualified-cli"); + assertEquals(QualificationState.unknown, select(List.of(current), evidence).state()); + install("new-headless", "new-runtime"); + var incomplete = new AssetCapacityProfiles.Bundle(current.profile(), Map.of("prometeu", hash("cli"))); + assertEquals(QualificationState.unknown, select(List.of(incomplete), evidence).state()); + } + + @Test void missingInstallationOrCatalogRemainsUnknown() throws Exception { + var service = new AssetCapacityProfiles(json, name -> null); + assertEquals(QualificationState.unknown, service.select(null).state()); + assertEquals(QualificationState.unknown, service.select(ProjectLocalStudioSetup.defaults()).state()); + install("headless", "runtime"); + assertEquals(QualificationState.unknown, service.select(setup()).state()); + } + + private AssetCapacityProfiles.Bundle bundle(String id, String headless, String runtime) { + var profile = new Profile(1, id, "test", hash("cli"), Map.of(BankType.glyph, 16), + List.of(new BoundaryEvidence(BankType.glyph, 16, 17, "evidence.json", AssetWorkspaceFiles.hash(evidence)))); + return new AssetCapacityProfiles.Bundle(profile, Map.of("prometeu", hash("cli"), + "prometeu-headless", hash(headless), "prometeu-runtime", hash(runtime))); + } + + private ProfileSelection select(List bundles, byte[] record) throws Exception { + byte[] catalog = json.writeValueAsBytes(new AssetCapacityProfiles.Catalog(1, bundles)); + return new AssetCapacityProfiles(json, name -> { + byte[] bytes = name.equals("asset-capacity/catalog.json") ? catalog : record; + return bytes == null ? null : new ByteArrayInputStream(bytes); + }).select(setup()); + } + + private ProjectLocalStudioSetup setup() { return new ProjectLocalStudioSetup(installation.toString(), null); } + private void install(String headless, String runtime) throws Exception { + Files.writeString(installation.resolve(executable("prometeu")), "cli"); + Files.writeString(installation.resolve(executable("prometeu-headless")), headless); + Files.writeString(installation.resolve(executable("prometeu-runtime")), runtime); + } + private static String executable(String name) { return name + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : ""); } + private static String hash(String text) { return AssetWorkspaceFiles.hash(text.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } +} diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java index c386575d..868a25f8 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java @@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class InstalledKnowledgeTest { @TempDir Path outsideRepository; diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/TargetBuildIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/TargetBuildIntegrationTest.java index 17742f7a..cf47d58a 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/TargetBuildIntegrationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/TargetBuildIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; /** Real compiler/packer/project composition, no guest or runtime installation required. */ +@org.junit.jupiter.api.Tag("integration") class TargetBuildIntegrationTest { @TempDir Path root; ConfigurableApplicationContext app;ProjectSession project;TaskTools tools;String task;ObjectMapper mapper; diff --git a/prometeu-app/src/test/java/p/studio/app/evidence/EvidenceIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/evidence/EvidenceIntegrationTest.java index ace2a220..9a4fb96e 100644 --- a/prometeu-app/src/test/java/p/studio/app/evidence/EvidenceIntegrationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/evidence/EvidenceIntegrationTest.java @@ -16,6 +16,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class EvidenceIntegrationTest { @TempDir Path root; ExecutorService pool;DefaultAutomationSession session;ProjectAccessRegistry projects;ObjectMapper mapper=new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java b/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java index 9e234370..424830ca 100644 --- a/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java +++ b/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java @@ -11,6 +11,7 @@ import java.util.*; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class InstalledConnectorTest { @TempDir Path temporary; @Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception { @@ -67,12 +68,15 @@ class InstalledConnectorTest { return builder; } public static class DesktopProbe { - public static void main(String[] args) { + public static void main(String[] args) throws Exception { + var application=new p.studio.app.App();application.init(); javafx.application.Platform.startup(() -> { try { - var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX"))); - stage.show(); stage.close(); System.exit(0); - } catch (Throwable failure) { System.exit(2); } + var stage = new javafx.stage.Stage();application.start(stage); + if(stage.getScene().lookup("#studio-shell")==null||stage.getScene().lookup("#open-project")==null) + throw new AssertionError("Installed app did not open the new project chooser"); + application.stop();stage.hide();System.exit(0); + } catch (Throwable failure) { failure.printStackTrace();System.exit(2); } }); } } diff --git a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java index 6c3270a6..e1670b43 100644 --- a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java +++ b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java @@ -17,6 +17,7 @@ import java.util.*; import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class AutomationLspQueriesTest { String httpAuthorization; @TempDir Path temporary; diff --git a/prometeu-app/src/test/java/p/studio/app/lsp/LanguageFailureContractTest.java b/prometeu-app/src/test/java/p/studio/app/lsp/LanguageFailureContractTest.java index c2399b45..3d792bb6 100644 --- a/prometeu-app/src/test/java/p/studio/app/lsp/LanguageFailureContractTest.java +++ b/prometeu-app/src/test/java/p/studio/app/lsp/LanguageFailureContractTest.java @@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.jupiter.api.Assertions.*; /** Controlled protocol faults use real sockets; the stubborn child is an explicitly injected port. */ +@org.junit.jupiter.api.Tag("integration") class LanguageFailureContractTest { @TempDir Path root; @Test void protocolMechanismsBecomeNeutralFailuresAndLegacyFallbackStaysLimited() throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/lsp/LspDiscoveryTest.java b/prometeu-app/src/test/java/p/studio/app/lsp/LspDiscoveryTest.java index 349c63d4..63a7256d 100644 --- a/prometeu-app/src/test/java/p/studio/app/lsp/LspDiscoveryTest.java +++ b/prometeu-app/src/test/java/p/studio/app/lsp/LspDiscoveryTest.java @@ -8,6 +8,7 @@ import p.studio.lsp.services.LspServerLifecycleImpl; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class LspDiscoveryTest { @TempDir Path root; final ObjectMapper mapper = new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java index 19476fdd..fcb1e118 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java @@ -10,6 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger; import p.studio.api.automation.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class LocalMcpServerTest { final ObjectMapper mapper = new ObjectMapper(); final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build(); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java index bf6bf5ac..72e811b4 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java @@ -13,6 +13,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class McpConnectionGuideTest { @TempDir Path root; @Test void preparationIsStableAndSeparateFromAuthority() throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java index ad3899d8..c6f332fa 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.atomic.*; import java.util.function.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class McpTaskToolsTest { String httpAuthorization; @TempDir Path root; diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java index c7371644..192493be 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java @@ -8,6 +8,7 @@ import java.nio.file.attribute.PosixFilePermissions; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class ProjectConnectionPublisherTest { @TempDir Path temporary; final ObjectMapper mapper = new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/StructuredDiagnosticsIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/StructuredDiagnosticsIntegrationTest.java index 2c0af236..591a6ae2 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/StructuredDiagnosticsIntegrationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/StructuredDiagnosticsIntegrationTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** Frozen sources, production compiler/packer/LSP, authenticated loopback MCP. No runtime execution. */ +@org.junit.jupiter.api.Tag("integration") class StructuredDiagnosticsIntegrationTest { @TempDir Path temporary; final ObjectMapper json = new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java index 7adb05bd..93e1aeb6 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java @@ -11,6 +11,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class StudioMcpStdioTest { @TempDir Path temporary; final ObjectMapper mapper = new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/AssetCapacityInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/AssetCapacityInstalledRuntimeTest.java index 32fa5ece..31c0eee5 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/AssetCapacityInstalledRuntimeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/AssetCapacityInstalledRuntimeTest.java @@ -10,6 +10,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; /** Provider qualification precedes publication of a consumer capacity profile. No managed-guard bypass in production. */ +@org.junit.jupiter.api.Tag("integration") class AssetCapacityInstalledRuntimeTest { @TempDir Path root; @Test void actualInstalledPoolsAcceptSixteenAndRejectSeventeenGlyphAndScenePreloads()throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/AssetManagedBuildInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/AssetManagedBuildInstalledRuntimeTest.java index 5090454f..73971758 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/AssetManagedBuildInstalledRuntimeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/AssetManagedBuildInstalledRuntimeTest.java @@ -16,6 +16,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** Real qualified build/preflight and process execution, independent of the provider boundary qualification. */ +@org.junit.jupiter.api.Tag("integration") class AssetManagedBuildInstalledRuntimeTest { @TempDir Path root; Map files(Path directory)throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestPilotTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestPilotTest.java index 2fe4643f..2648ac09 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestPilotTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestPilotTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; /** Required pilot on a disposable copy of the actual game, using only its existing public APIs. */ +@org.junit.jupiter.api.Tag("integration") class GuestTestPilotTest { @TempDir Path root; static Map sources(Path root)throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsDesktopTest.java index d503ab8b..dabd5928 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsDesktopTest.java @@ -28,6 +28,7 @@ import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.*; /** Actual Tests workspace + authenticated HTTP MCP + installed provider, over one service. */ +@org.junit.jupiter.api.Tag("integration") class GuestTestsDesktopTest { @TempDir Path root; @BeforeAll static void toolkit()throws Exception {var ready=new CompletableFuture();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(10,TimeUnit.SECONDS);} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsInstalledRuntimeTest.java index 6d9924cb..399bd797 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsInstalledRuntimeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/GuestTestsInstalledRuntimeTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; /** Actual installed provider and PBS/compiler/packer/shared runner; no simulated protocol. */ +@org.junit.jupiter.api.Tag("integration") class GuestTestsInstalledRuntimeTest { @TempDir Path root; ConfigurableApplicationContext app;ProjectSession session;GuestTestTools tests;ObjectMapper mapper;String task; diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java index 91b17bda..78fc56ca 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java @@ -15,6 +15,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** Explicit packaged-process gate, not satisfied by protocol fixtures. */ +@org.junit.jupiter.api.Tag("integration") class HeadlessInstalledRuntimeTest { @TempDir Path root; @Test void configuredDistributionBootsSavedBuildAndReturnsDeterministicCanonicalPixels() throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java index 4877d7d6..96bab06b 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java @@ -30,6 +30,7 @@ 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. */ +@org.junit.jupiter.api.Tag("integration") class HeadlessMcpDesktopTest { @TempDir Path root; final ObjectMapper mapper = new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java index 9fa6800e..f9d85424 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java @@ -10,6 +10,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class HeadlessProcessSessionTest { @TempDir Path root; final List sessions = new ArrayList<>(); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java index a5930c80..c2c9ab30 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessTaskIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; /** Actual app composition and saved-source services; no runtime/build/LSP doubles. */ +@org.junit.jupiter.api.Tag("integration") class HeadlessTaskIntegrationTest { @TempDir Path root; ConfigurableApplicationContext app; @@ -120,12 +121,16 @@ class HeadlessTaskIntegrationTest { System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(Map.of("kind","native-checkpoint","artifact",artifact,"report",report.report(),"nativeAdvanceRequests",2,"persistenceExtraAdvanceOrCaptureRequests",0))); } - @Test void zeldaPilotUsesDisposableCopyAndKeepsReferenceLimitationsExplicit() throws Exception { - Path originalProject=Path.of(System.getProperty("studio.test.zeldaProject", "../../zelda-1")).toAbsolutePath().normalize(); - assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Zelda pilot checkout is required for this qualification"); - project.close();Path copy=root.resolve("zelda-pilot");Files.createDirectories(copy); + @Test void pongPilotUsesDisposableCopyAndIndependentRegionReferences() throws Exception { + String fixture=System.getProperty("studio.test.pong"); + assertNotNull(fixture,"Run headlessProcessTest to select Studio's test-projects/pong fixture"); + Path originalProject=Path.of(fixture).toAbsolutePath().normalize(); + assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Repository-owned Pong fixture is required"); + String originalSource=Files.readString(originalProject.resolve("src/main.pbs")); + project.close();Path copy=root.resolve("Pong Headless");Files.createDirectories(copy); for(String name:List.of("prometeu.json","src","assets")) { Path from=originalProject.resolve(name); + if(!Files.exists(from))continue; // Pong has no external assets. if(Files.isDirectory(from))try(var paths=Files.walk(from)) { for(var p:paths.toList()){var target=copy.resolve(originalProject.relativize(p));if(Files.isDirectory(p))Files.createDirectories(target);else Files.copy(p,target);} }else Files.copy(from,copy.resolve(name)); @@ -133,17 +138,20 @@ class HeadlessTaskIntegrationTest { root=copy.toRealPath();var ref=app.getBean(ProjectCatalog.class).openProject(root); app.getBean(ProjectLocalStudioSetupStore.class).save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null)); project=app.getBean(ProjectSessionFactory.class).open(ref);project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tasks.acquire(root).task().value(); - String build=successfulBuild("zelda-pilot-build");tasks.headless(root,task,TaskTools.HeadlessAction.BOOT,build,Map.of("memcardChoice","memory_fresh")); + String build=successfulBuild("pong-pilot-build");call(TaskTools.HeadlessAction.BOOT,build); var evidence=app.getBean(EvidenceTools.class);var measurements=new ArrayList>(); var mcp=app.getBean(p.studio.app.mcp.McpToolRegistry.class); long beforeWireBytes=0,afterWireBytes=0;int beforeCalls=0,afterCalls=0; var legacyPaths=new ArrayList(); - String[] refs={"extracted/inventory_screen/validation/production_start.png","extracted/hud/runtime_initial.png","extracted/bomb_wall/validation/scroll_north_mid.png"}; - String[] names={"screen","hud","scroll"}; + String[] names={"menu-accent","serve-ball","moved-paddle"}; + // Fixed expectations from the fixture's draw/input contract, never from a native capture. + Evidence.Rect[] regions={new Evidence.Rect(113,114,1,80),new Evidence.Rect(237,152,6,6),new Evidence.Rect(42,72,8,36)}; + int[][] colors={{77,237,205},{236,244,250},{77,237,205}}; long totalPngBytes=0; for(int i=0;i0)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of(i==1?"start":"right",true)); - String request="zelda-"+names[i];tasks.advance(root,task,request,i==0?1:i==1?76:120);var operation=finished(request); + if(i==1)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",true)); + if(i==2)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",false,"up",true)); + String request="pong-"+names[i];tasks.advance(root,task,request,i==2?20:1);var operation=finished(request); assertNull(operation.failure());assertNotNull(operation.runtimeResult().capture()); var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task); var before=mcp.call("studio_operation_get",args.deepCopy().put("clientRequestId",request)).wire(); @@ -154,13 +162,18 @@ class HeadlessTaskIntegrationTest { afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(persisted).length; assertFalse(persisted.path("isError").asBoolean(),persisted.toString()); var actual=mapper.convertValue(persisted.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst(); - Path reference=root.resolve("reference-"+names[i]+".png");Files.copy(originalProject.resolve(refs[i]),reference); + Path reference=root.resolve("reference-"+names[i]+".png"); + byte[] rgba=new byte[480*270*4]; + for(int pixel=0;pixel(List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),script.toString()));command.addAll(legacyPaths); var legacy=new ProcessBuilder(command).redirectErrorStream(true).start();assertTrue(legacy.waitFor(30,TimeUnit.SECONDS)); String legacyOutput=new String(legacy.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);assertEquals(0,legacy.exitValue(),legacyOutput); - var output=Map.of("kind","zelda-pilot","limitations","Saved port captures are contextual references, not an independent NES oracle; screen/HUD/scroll reference labels identify their provenance. Current checkpoints are observations and mismatch is retained as a comparison result.", + assertEquals(originalSource,Files.readString(originalProject.resolve("src/main.pbs")),"Build and runtime must use only the disposable copy"); + var output=Map.of("kind","pong-pilot","limitations","Solid-color references specify only the declared ROIs independently of native captures. These checks cover menu, serve and input-driven paddle movement, not full-game visual equivalence.", "results",measurements,"measurement",Map.of("sharedGuestAdvanceRequests",3,"before",Map.of("mcpCalls",beforeCalls,"wireResponseBytes",beforeWireBytes,"imagePngBytes",totalPngBytes,"externalComparisonScripts",1,"externalScriptOutput",legacyOutput), "after",Map.of("mcpCalls",afterCalls,"wireResponseBytes",afterWireBytes,"imageTransferBytesForMetrics",0,"externalComparisonScripts",0), - "basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from the explicit HUD ROI by design.")); + "basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from ROI-specific checks by design.")); System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(output)); } diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/MemcardInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/MemcardInstalledRuntimeTest.java index 075ac278..5c3d58fc 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/MemcardInstalledRuntimeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/MemcardInstalledRuntimeTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** PBS/shipper -> configured dispatcher -> distinct OS processes; no native injection. */ +@org.junit.jupiter.api.Tag("integration") class MemcardInstalledRuntimeTest { @TempDir Path root; final ObjectMapper mapper = new ObjectMapper(); diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/StudioPlayInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/StudioPlayInstalledRuntimeTest.java new file mode 100644 index 00000000..75032580 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/StudioPlayInstalledRuntimeTest.java @@ -0,0 +1,82 @@ +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.execution.*; +import p.studio.api.project.*; +import p.studio.api.automation.TaskTools; +import p.studio.api.runtime.RuntimeLogEntry; +import p.studio.core.project.*; +import p.studio.core.runtime.*; +import p.studio.core.shipper.StudioShipperService; +import p.studio.app.compiler.CompilerBuildGatewayAdapter; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.app.runtime.studio.StudioRuntimeGateway; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Cross-mode save compatibility and actual interactive dirty-Stop refusal. */ +@org.junit.jupiter.api.Tag("integration") +class StudioPlayInstalledRuntimeTest { + @TempDir Path root; + final ObjectMapper json=new ObjectMapper(); + @Test void persistentDirtyStopRefusesThenGuestCommitsAndHeadlessReadsWhileDisposableNeverOverwrites()throws Exception{ + Files.createDirectories(root.resolve("src")); + Files.writeString(root.resolve("prometeu.json"),""" + {"name":"studio-save","version":"1","language":"pbs","stdlib":"1","target":"Game","app_id":4294967295,"memcard_slots":1,"dependencies":[]} + """); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;"); + String writer=MemcardInstalledRuntimeTest.WRITER + .replace(MemcardInstalledRuntimeTest.PREFIX,MemcardInstalledRuntimeTest.PREFIX+"import {Pad, Button} from @sdk:input;\n") + .replace("let commit = Mem.slot_commit(context, 0);","if Pad.down(Button.A) == false { return; }\nlet commit = Mem.slot_commit(context, 0);"); + Files.writeString(root.resolve("src/main.pbs"),writer); + var store=new ProjectLocalStudioSetupStore(json);var project=new ProjectCatalogService(root,json,store).openProject(root); + Path image=root.resolve("development-save.pmc");var setup=new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null,null,image.toString());store.save(project,setup); + var logs=new CopyOnWriteArrayList(); + try(var workers=Executors.newFixedThreadPool(2);var packer=p.packer.Packer.bootstrap(json,e->{})){ + var shipper=new StudioShipperService(new CompilerBuildGatewayAdapter(),packer.workspaceService(),json,new ExecutorOperationExecutor(workers)) + .withAssetPreflight(new p.studio.app.assets.AssetBudgetInspection(json,packer.workspaceService(),store::load)); + var build=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);assertTrue(build.success(),build.diagnostics().toString()); + var headless=new HeadlessProcessGateway(json,store::load); + var formatting=(HeadlessProcessSession)headless.boot(project,"format-test-media",build, + Map.of("memcard",Map.of("path",image.toString(),"action","create","access","read_write"),"memcardChoice","persistent")); + try{formatting.call(TaskTools.HeadlessAction.RESET,Map.of("discardUnsaved",true,"pendingWrites","cancel"));} + finally{formatting.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);} + assertTrue(Files.isRegularFile(image)); + var gateway=new StudioRuntimeGateway(json); + var persistent=gateway.start(project,setup,logs::add,PlayOptions.PERSISTENT); + try{ + persistent.startExecution().get(5,TimeUnit.SECONDS);awaitColor(persistent,0,0,255,logs); // BGRA red + var refusal=assertThrows(ExecutionException.class,()->persistent.stopAsync().get(5,TimeUnit.SECONDS)); + assertInstanceOf(RuntimeStopRefusedException.class,refusal.getCause());assertFalse(persistent.completion().isDone()); + persistent.resume().get(5,TimeUnit.SECONDS);persistent.input(new ExecutionInput(16,0,0)); + awaitColor(persistent,0,255,0,logs);persistent.input(ExecutionInput.NEUTRAL); + persistent.stopAsync().get(5,TimeUnit.SECONDS);assertEquals(0,persistent.completion().join()); + }finally{if(!persistent.completion().isDone()){persistent.resume().get(5,TimeUnit.SECONDS);persistent.input(new ExecutionInput(16,0,0));awaitColor(persistent,0,255,0,logs);persistent.stopAsync().get(5,TimeUnit.SECONDS);}} + byte[] saved=Files.readAllBytes(image); + var disposable=gateway.start(project,setup,logs::add,new PlayOptions(true)); + try{disposable.startExecution().get(5,TimeUnit.SECONDS);awaitColor(disposable,0,0,255,logs);disposable.stopAsync().get(5,TimeUnit.SECONDS);} + finally{disposable.close();} + assertArrayEquals(saved,Files.readAllBytes(image),"Explicit disposable Play must leave selected persistent media intact"); + Files.writeString(root.resolve("src/main.pbs"),MemcardInstalledRuntimeTest.READER); + var readBuild=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);assertTrue(readBuild.success(),readBuild.diagnostics().toString()); + var reader=(HeadlessProcessSession)headless.boot(project,"read-studio-save",readBuild, + Map.of("memcard",Map.of("path",image.toString(),"action","open","access","read_write"),"memcardChoice","persistent")); + try{assertEquals(p.studio.api.automation.AutomationOutcome.Kind.SUCCEEDED,reader.advance(1,e->{}).kind());} + finally{reader.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);} + assertArrayEquals(saved,Files.readAllBytes(image),"Headless reader must not resave"); + var missing=new ProjectLocalStudioSetup(setup.prometeuRuntimePath(),null,null,root.resolve("absent.pmc").toString()); + assertThrows(java.io.IOException.class,()->gateway.start(project,missing,logs::add,PlayOptions.PERSISTENT));assertFalse(Files.exists(root.resolve("absent.pmc"))); + } + } + static void awaitColor(RuntimeConnection connection,int b,int g,int r,List logs)throws Exception{ + long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(5); + while(System.nanoTime() logs=new CopyOnWriteArrayList<>(); + Process process;Socket control,video;StudioRuntimeConnection connection; + Native()throws Exception { + try(ServerSocket c=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1")); + ServerSocket v=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"))){ + process=new ProcessBuilder(System.getProperty("studio.test.studioHost"),"--studio","--run", + System.getProperty("studio.test.studioCartridge")).start(); + var stdout=StudioRuntimeGateway.drain(process.getInputStream(),false,e->logs.add(e.message()),io); + var stderr=StudioRuntimeGateway.drain(process.getErrorStream(),true,e->logs.add(e.message()),io); + byte[] session=new byte[16],token=new byte[32];Arrays.fill(session,(byte)3);Arrays.fill(token,(byte)7); + try(var input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,little(53) + .put(session).put(token).putShort((short)c.getLocalPort()).putShort((short)v.getLocalPort()).put((byte)1).array());} + c.setSoTimeout(10000);v.setSoTimeout(10000);control=c.accept();video=v.accept(); + control.setSoTimeout(10000);video.setSoTimeout(10000); + Reader cr=new Reader(control.getInputStream()),vr=new Reader(video.getInputStream()); + assertEquals(HELLO,cr.receive().header().kind());assertEquals(HELLO,vr.receive().header().kind()); + var ready=cr.receive();assertEquals(READY,ready.header().kind()); + var b=ByteBuffer.wrap(ready.payload()).order(ByteOrder.LITTLE_ENDIAN);int width=b.getInt(),height=b.getInt(); + control.setSoTimeout(0);video.setSoTimeout(0); + connection=new StudioRuntimeConnection(process,control,video,cr,vr,session,width,height,e->logs.add(e.message()),io,stdout,stderr); + }catch(Throwable failure){close();throw failure;} + } + ExecutionFrame image()throws Exception { + long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(3); + while(System.nanoTime()first+1);} + s.connection.pause().get(3,TimeUnit.SECONDS);Thread.sleep(40); + try(var finalFrame=s.connection.acquireLatestFrame()){/* Drain an asynchronous final publication. */} + Thread.sleep(40);assertNull(s.connection.acquireLatestFrame()); + s.connection.resume().get(3,TimeUnit.SECONDS);try(var resumed=s.image()){assertTrue(resumed.frameId()>first);} + assertEquals(pid,s.process.pid());s.connection.stopAsync().get(5,TimeUnit.SECONDS); + assertEquals(0,s.connection.completion().get(1,TimeUnit.SECONDS));assertFalse(s.process.isAlive()); + assertTrue(s.logs.stream().anyMatch(line->line.contains("Runtime stopped"))); + } + } + @Test void pauseBeforeStartWaitsForExplicitResume()throws Exception { + try(var s=new Native()){ + s.connection.pause().get(3,TimeUnit.SECONDS);s.connection.startExecution().get(3,TimeUnit.SECONDS); + Thread.sleep(80);assertNull(s.connection.acquireLatestFrame()); + s.connection.resume().get(3,TimeUnit.SECONDS);try(var image=s.image()){assertEquals(480,image.width());} + s.connection.stopAsync().get(5,TimeUnit.SECONDS); + } + } + @Test void brokenVideoAndControlKillTheOwnedProcessAndKeepLogs()throws Exception { + for(boolean video:new boolean[]{true,false})try(var s=new Native()){ + s.connection.startExecution().get(3,TimeUnit.SECONDS); + if(video)s.video.close();else s.control.close(); + assertThrows(ExecutionException.class,()->s.connection.completion().get(4,TimeUnit.SECONDS)); + assertFalse(s.process.isAlive());assertTrue(s.logs.stream().anyMatch(line->line.contains("connection failed"))); + } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/studio/StudioWireTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/studio/StudioWireTest.java new file mode 100644 index 00000000..1cdbf56a --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/studio/StudioWireTest.java @@ -0,0 +1,60 @@ +package p.studio.app.runtime.studio; + +import org.junit.jupiter.api.Test; +import java.io.*; +import java.nio.file.*; +import java.util.HexFormat; +import p.studio.app.runtime.studio.StudioWire.Reader; +import static org.junit.jupiter.api.Assertions.*; +import static p.studio.app.runtime.studio.StudioWire.*; + +class StudioWireTest { + @Test void blankNativeLinesDoNotStopBoundedLogDrain() { + var logs=new java.util.ArrayList(); + String output="\n \r\nready\n"+"x".repeat(9000)+"\nlast"; + StudioRuntimeGateway.drain(new ByteArrayInputStream(output.getBytes(java.nio.charset.StandardCharsets.UTF_8)),false,logs::add,Runnable::run).join(); + assertEquals(3,logs.size());assertEquals("ready",logs.getFirst().message()); + assertEquals(8193,logs.get(1).message().length());assertEquals("last",logs.getLast().message()); + } + private byte[] fixture() throws IOException { + String hex=Files.readString(Path.of(System.getProperty("studio.test.protocolFixtures"),"pause.hex")); + return HexFormat.of().parseHex(hex.replaceAll("\\s+","")); + } + @Test void headerMatchesSharedRustFixture() throws Exception { + assertArrayEquals(fixture(),new Header(PAUSE,0,1,42).encode()); + assertEquals(42,Header.decode(fixture()).request()); + } + @Test void fragmentedReadsWorkButTruncationAndReplayFail() throws Exception { + byte[] bytes=fixture(); + InputStream fragmented=new FilterInputStream(new ByteArrayInputStream(bytes)) { + @Override public int read(byte[] b,int off,int len)throws IOException {return super.read(b,off,Math.min(len,3));} + }; + assertEquals(PAUSE,new Reader(fragmented).receive().header().kind()); + assertThrows(EOFException.class,()->new Reader(new ByteArrayInputStream(bytes,0,31)).receive()); + var twice=new ByteArrayOutputStream();twice.write(bytes);twice.write(bytes); + var reader=new Reader(new ByteArrayInputStream(twice.toByteArray()));reader.receive(); + assertThrows(IOException.class,reader::receive); + } + @Test void validatesBeforeAllocatingPayload() throws Exception { + for(int offset:new int[]{0,4,6,8,10}) {byte[] bad=fixture();bad[offset]=(byte)255; + assertThrows(IOException.class,()->Header.decode(bad));} + byte[] huge=fixture();java.util.Arrays.fill(huge,12,16,(byte)255); + assertThrows(IOException.class,()->Header.decode(huge)); + assertThrows(IOException.class,()->frameBytes(Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE)); + assertThrows(IOException.class,()->frameBytes(480,270,481)); + assertEquals(518400,frameBytes(480,270,480)); + assertThrows(IOException.class,()->text(new byte[]{(byte)0xff},0)); + } + @Test void rgbaPayloadMatchesSharedFixture() throws Exception { + byte[] bytes=HexFormat.of().parseHex(Files.readString(Path.of( + System.getProperty("studio.test.protocolFixtures"),"rgba.hex")).replaceAll("\\s+","")); + var reader=new Reader(new ByteArrayInputStream(bytes));var h=reader.nextHeader(); + assertEquals(FRAME,h.kind());assertEquals(56,h.length()); + byte[] metadata=new byte[48];reader.readFully(metadata,0,48); + var b=java.nio.ByteBuffer.wrap(metadata).order(java.nio.ByteOrder.LITTLE_ENDIAN); + b.position(16);assertEquals(1,b.getLong());assertEquals(7,b.getLong()); + int width=b.getInt(),height=b.getInt(),stride=b.getInt();assertEquals(RGBA8,b.getInt()); + byte[] pixels=new byte[frameBytes(width,height,stride)];reader.readFully(pixels,0,pixels.length); + assertArrayEquals(HexFormat.of().parseHex("ff0000ff0000ff80"),pixels); + } +} diff --git a/prometeu-architecture-tests/build.gradle.kts b/prometeu-architecture-tests/build.gradle.kts index b48794a6..3bba54e3 100644 --- a/prometeu-architecture-tests/build.gradle.kts +++ b/prometeu-architecture-tests/build.gradle.kts @@ -19,6 +19,7 @@ dependencies { testImplementation(project(":prometeu-studio-api")) testImplementation(project(":prometeu-studio-core")) testImplementation(project(":prometeu-studio-ui-javafx")) + testImplementation(project(":prometeu-studio-ui-javafx-2")) testImplementation(project(":prometeu-app")) } diff --git a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java index 87c88cfe..82f602f9 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java @@ -70,7 +70,7 @@ class StudioBoundaryArchTest { @ArchTest static final ArchRule javaFxAdapterDoesNotDependOnCoreOrProviderImplementations = noClasses() - .that().resideInAPackage("p.studio.ui.javafx..") + .that().resideInAnyPackage("p.studio.ui.javafx..", "p.studio.ui.javafx2..") .should().dependOnClassesThat().resideInAnyPackage( "p.studio.core..", "p.packer..", @@ -81,13 +81,13 @@ class StudioBoundaryArchTest { @ArchTest static final ArchRule javaFxAdapterDoesNotOrchestrateTheFileSystem = noClasses() - .that().resideInAPackage("p.studio.ui.javafx..") + .that().resideInAnyPackage("p.studio.ui.javafx..", "p.studio.ui.javafx2..") .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..") + .that().resideInAnyPackage("p.studio.ui.javafx..", "p.studio.ui.javafx2..") .should().dependOnClassesThat().resideInAPackage("com.fasterxml.jackson..") .because("DEC-0059 keeps serialization in core or application adapters, not visual controls"); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsClosuresTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsClosuresTest.java index b3f12aef..af14d3e8 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsClosuresTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsClosuresTest.java @@ -6,6 +6,7 @@ import p.studio.compiler.source.diagnostics.DiagnosticSink; import p.studio.compiler.source.identifiers.FileId; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsClosuresTest { @Test void namedAndAnonymousFunctionsShareSignature() throws Exception { PbsStructuredValuesTest.compile("closure-functions", """ diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericContractsTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericContractsTest.java index dd61b050..399b0505 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericContractsTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericContractsTest.java @@ -13,6 +13,7 @@ import p.studio.utilities.structures.ReadOnlyList; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsGenericContractsTest { private static final String ECHO = "declare contract Echo { fn echo(value: T) -> T; } declare service Strategy {}\n"; diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java index ba48c5c7..de6e8e13 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java @@ -12,6 +12,7 @@ import p.studio.utilities.structures.ReadOnlyList; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsGenericStructsTest { private static final String BOX = """ declare struct Box(value: T) { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java index 09ff7489..1b36e2bb 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java @@ -18,6 +18,7 @@ import java.nio.file.*; import java.util.List; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsGuestLifecycleTest { private static Path directory() { return Path.of(System.getProperty("pbs.registryConformanceDirectory")); } private static final String BASE = """ diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsIdentityHashingTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsIdentityHashingTest.java index f07507de..dd034890 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsIdentityHashingTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsIdentityHashingTest.java @@ -10,6 +10,7 @@ import java.nio.file.*; import java.util.HexFormat; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsIdentityHashingTest { static String sdk() throws Exception { try(var stream=PbsIdentityHashingTest.class.getResourceAsStream("/game/stdlib/1/sdk/hash/main.pbs")) { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java index 113de20a..93f728cd 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java @@ -6,6 +6,7 @@ import java.nio.file.*; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsLinkedTest { static void compile(String name, String source) throws Exception { PbsListCursorTest.compileCollection("linked", name, source); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java index 2617978a..8c31a447 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java @@ -15,6 +15,7 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsListCursorTest { private static Path directory() { return Path.of(System.getProperty("pbs.registryConformanceDirectory")); } static BytecodeModule compile(String name,String source) throws Exception { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMapKeyvalTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMapKeyvalTest.java index cda2a5b2..1c881fd9 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMapKeyvalTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMapKeyvalTest.java @@ -6,6 +6,7 @@ import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsMapKeyvalTest { static void compile(String name,String source)throws Exception { PbsListCursorTest.compileCollection("map",name,source); } static void probe(String name,String body)throws Exception { compile(name,"declare service Probe {fn main()->int {"+body+"}}"); } diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMemcardTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMemcardTest.java index 00de1d82..e80de928 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMemcardTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMemcardTest.java @@ -11,6 +11,7 @@ import java.nio.file.*; import java.util.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsMemcardTest { @TempDir Path root; private CompileResult compile(Path project) { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java index ac9ca151..91169f69 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java @@ -8,6 +8,7 @@ import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*; /** Production producers; results are independently checked by the native verifier. */ +@org.junit.jupiter.api.Tag("integration") class PbsResultTest { @Test void resultFunctionsCannotBecomePlainFunctionValues() { for(String value:new String[]{"let f:Fn()->int=fallible;","let f=fallible;"}){ diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java index f803af15..4015a089 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java @@ -10,6 +10,7 @@ import p.studio.compiler.models.SourceKind; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsRuntimeAlignmentTest { private static String sdk(String path) throws Exception { try(var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/"+path+"/main.pbs")) { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java index d337f0a0..6eb1caaf 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java @@ -7,6 +7,7 @@ import p.studio.compiler.source.identifiers.FileId; import p.studio.compiler.models.SourceKind; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsRuntimeMathTest { static String sdk() throws Exception { var result = new StringBuilder(); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java index 266b9a69..b6cda8f3 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import p.studio.compiler.pbs.PbsFrontendCompiler; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsRuntimeRandomTest { static String sdk() throws Exception { try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/sdk/random/main.pbs")) { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java index 9aff587b..92b090d2 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java @@ -12,6 +12,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.*; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsSetTest { static String sdk() throws Exception { try(var stream=PbsSetTest.class.getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java index 45bb8967..1ddb0060 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java @@ -6,6 +6,7 @@ import p.studio.compiler.pbs.PbsFrontendCompiler; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsSpriteAnimationTest { static String core() throws Exception { var text = new StringBuilder(); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java index 94aea25f..2f2f1c13 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java @@ -6,6 +6,7 @@ import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsStackQueueTest { private static void compile(String type,String name,String source) throws Exception { PbsListCursorTest.compileCollection(type,name,source); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java index d8bddc64..973e80ff 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java @@ -14,6 +14,7 @@ import p.studio.utilities.structures.ReadOnlyList; import p.studio.compiler.source.identifiers.ModuleId; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class PbsStructuredValuesTest { static BytecodeModule compile(String name,String source) throws Exception { var diagnostics=DiagnosticSink.empty(); diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/BackendGateIIntegrationTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/BackendGateIIntegrationTest.java index 4aed69e3..914e3ea9 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/BackendGateIIntegrationTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/BackendGateIIntegrationTest.java @@ -29,6 +29,7 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.*; @Disabled("tests for gate I validation of emitted bytecode, requires direct construction of IRBackend and BytecodeModule instances") +@org.junit.jupiter.api.Tag("integration") class BackendGateIIntegrationTest { private final RuntimeCompatibilityAdapter compatibilityAdapter = RuntimeCompatibilityAdapters.createDefault(); diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/MainProjectPipelineIntegrationTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/MainProjectPipelineIntegrationTest.java index 770e6656..c57ad9f4 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/MainProjectPipelineIntegrationTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/MainProjectPipelineIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.*; @Disabled("integration test for main project pipeline, requires test-projects/main to be present in the repository") +@org.junit.jupiter.api.Tag("integration") class MainProjectPipelineIntegrationTest { @Test diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/PbsFacadeDiagnosticTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/PbsFacadeDiagnosticTest.java index 4f6bf3c4..862745bc 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/PbsFacadeDiagnosticTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/PbsFacadeDiagnosticTest.java @@ -17,6 +17,7 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.*; /** Exact source fixtures from AGD-0113: this qualifies diagnostics, not the PBS fix. */ +@org.junit.jupiter.api.Tag("integration") class PbsFacadeDiagnosticTest { @TempDir Path root; diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/RuntimeBackedCompatibilityAdapterTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/RuntimeBackedCompatibilityAdapterTest.java index a0713bb5..bf066425 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/RuntimeBackedCompatibilityAdapterTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/RuntimeBackedCompatibilityAdapterTest.java @@ -14,6 +14,7 @@ import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +@org.junit.jupiter.api.Tag("integration") class RuntimeBackedCompatibilityAdapterTest { @Test diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/SyntheticFrontendPipelineTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/SyntheticFrontendPipelineTest.java index 3373271f..8adc163e 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/SyntheticFrontendPipelineTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/SyntheticFrontendPipelineTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +@org.junit.jupiter.api.Tag("integration") class SyntheticFrontendPipelineTest { @TempDir diff --git a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/ExternalSourceDevelopmentHostTest.java b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/ExternalSourceDevelopmentHostTest.java index 92cabee0..9fe8799b 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/ExternalSourceDevelopmentHostTest.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/ExternalSourceDevelopmentHostTest.java @@ -11,6 +11,7 @@ import static org.junit.jupiter.api.Assertions.*; /** Opt-in actual VS Code test against the development classpath (never installDist). */ @EnabledIfEnvironmentVariable(named = "PROMETEU_VSCODE_DEV_TEST", matches = "1") +@org.junit.jupiter.api.Tag("integration") class ExternalSourceDevelopmentHostTest { @TempDir Path temporary; diff --git a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java index f03f5114..cf9f6c51 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/LspServerLifecycleTest.java @@ -7,6 +7,7 @@ import java.nio.file.Path; import java.net.Socket; import static org.junit.jupiter.api.Assertions.*; +@org.junit.jupiter.api.Tag("integration") class LspServerLifecycleTest { private static final int INITIALIZATION_TIMEOUT_MS = 10_000; private static final int SHUTDOWN_TIMEOUT_MS = 2_000; diff --git a/prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerAssetContractTest.java b/prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerAssetContractTest.java index 4c8e4340..6259df79 100644 --- a/prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerAssetContractTest.java +++ b/prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerAssetContractTest.java @@ -26,6 +26,7 @@ import java.util.Objects; import static org.junit.jupiter.api.Assertions.*; /** Producer contract checks only: no runtime executable or runtime decoder. */ +@org.junit.jupiter.api.Tag("integration") final class PackerAssetContractTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final int[] COLORS = {0x123456ff, 0xabcdef80, 0x34567800, 0x876543ff}; diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ExecutionAuthority.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ExecutionAuthority.java new file mode 100644 index 00000000..9e9ffcec --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ExecutionAuthority.java @@ -0,0 +1,12 @@ +package p.studio.api.automation; + +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +/** Internal project admission port; not an agent capability or generic tool endpoint. */ +public interface ExecutionAuthority { + ManualLease enterExecution(); + boolean preparingExecution(); + T prepareExecution(Supplier work); + T callExecutionPreparation(Callable work) throws Exception; +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java index 114d10d7..2fdf58b7 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java @@ -6,6 +6,9 @@ public interface ProjectAccess { /** Execution owns the manual lane until its runtime has stopped. */ default ManualLease enterExecution(Path path) { return enterManual(path); } + /** Preparation is admitted by the existing execution owner, never by arbitrary UI writers. */ + default T prepareExecution(Path path, java.util.function.Supplier preparation) {return preparation.get();} + default p.studio.api.operation.OperationHandle submitManual(Path path, p.studio.api.operation.OperationExecutor executor, String summary, java.util.concurrent.Callable work) { ManualLease lease = enterManual(path); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionController.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionController.java index dc0fc54e..a922382f 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionController.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionController.java @@ -7,6 +7,16 @@ public interface ExecutionController extends AutoCloseable { void stop(); + default OperationHandle pause() { throw new UnsupportedOperationException("Pause unavailable"); } + default OperationHandle resume() { throw new UnsupportedOperationException("Resume unavailable"); } + default java.util.concurrent.CompletionStage stopAsync() { + stop(); return java.util.concurrent.CompletableFuture.completedFuture(null); + } + default ExecutionFrame acquireLatestFrame() { return null; } + default void input(ExecutionInput input) { } + /** True until preparation, process and cleanup have actually relinquished ownership. */ + default boolean ownsExecution() { return false; } + default void shutdown() { close(); } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionControllerFactory.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionControllerFactory.java index 0f6c22cf..01f1daa2 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionControllerFactory.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionControllerFactory.java @@ -5,4 +5,9 @@ import p.studio.api.project.ProjectReference; public interface ExecutionControllerFactory { ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session); + + default ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session, PlayOptions options) { + if (options.disposableSave()) throw new UnsupportedOperationException("Disposable Play unavailable"); + return create(project,setup,session); + } } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionFrame.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionFrame.java new file mode 100644 index 00000000..bc944ee0 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionFrame.java @@ -0,0 +1,30 @@ +package p.studio.api.execution; + +import java.nio.ByteBuffer; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** Exclusive lease of stable BGRA_PRE pixels. Copy before close; never retain pixels after close. */ +public final class ExecutionFrame implements AutoCloseable { + private final int width,height; + private final long id,epoch; + private final long receivedAtNanos; + private final ByteBuffer pixels; + private final Runnable release; + private final AtomicBoolean closed = new AtomicBoolean(); + public ExecutionFrame(int width,int height,long id,long epoch,byte[] pixels,Runnable release) { + this(width,height,id,epoch,pixels,System.nanoTime(),release); + } + public ExecutionFrame(int width,int height,long id,long epoch,byte[] pixels,long receivedAtNanos,Runnable release) { + if (width<=0 || height<=0 || pixels.length%4!=0 || (long)width*height!=pixels.length/4L) + throw new IllegalArgumentException("Invalid frame dimensions"); + this.width=width;this.height=height;this.id=id;this.epoch=epoch; + this.receivedAtNanos=receivedAtNanos; + this.pixels=ByteBuffer.wrap(pixels).asReadOnlyBuffer();this.release=Objects.requireNonNull(release); + } + public int width(){return width;} public int height(){return height;} + public long frameId(){return id;} public long epoch(){return epoch;} + public long receivedAtNanos(){return receivedAtNanos;} + public ByteBuffer pixels(){if(closed.get())throw new IllegalStateException("Frame released");return pixels.duplicate();} + @Override public void close(){if(closed.compareAndSet(false,true))release.run();} +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionInput.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionInput.java new file mode 100644 index 00000000..0ec71a48 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionInput.java @@ -0,0 +1,9 @@ +package p.studio.api.execution; + +/** Canonical pad/touch snapshot. Bits 0..11 are pad, bit 12 is touch. */ +public record ExecutionInput(int buttons, int touchX, int touchY) { + public static final ExecutionInput NEUTRAL = new ExecutionInput(0,0,0); + public ExecutionInput { + if ((buttons & ~0x1fff) != 0) throw new IllegalArgumentException("Unknown input bits"); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionSession.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionSession.java index c05a2eb0..b14cf21c 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionSession.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionSession.java @@ -19,6 +19,11 @@ public interface ExecutionSession extends AutoCloseable { void transitionToRunning(); + default void transitionToPausing() { throw new UnsupportedOperationException(); } + default void transitionToPaused() { throw new UnsupportedOperationException(); } + default void transitionToResuming() { throw new UnsupportedOperationException(); } + default void transitionToStopping() { throw new UnsupportedOperationException(); } + void transitionToRuntimeFailed(); void transitionToStopped(); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionState.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionState.java index 825f43c5..44917642 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionState.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/ExecutionState.java @@ -6,6 +6,10 @@ public enum ExecutionState { PREPARE_FAILED, CONNECTING, RUNNING, + PAUSING, + PAUSED, + RESUMING, + STOPPING, RUNTIME_FAILED, STOPPED } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/execution/PlayOptions.java b/prometeu-studio-api/src/main/java/p/studio/api/execution/PlayOptions.java new file mode 100644 index 00000000..94250465 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/execution/PlayOptions.java @@ -0,0 +1,6 @@ +package p.studio.api.execution; + +/** Explicit per-session save policy; persistent media is never implicitly discarded. */ +public record PlayOptions(boolean disposableSave) { + public static final PlayOptions PERSISTENT = new PlayOptions(false); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSessionFactory.java b/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSessionFactory.java index 7dfe2b9c..f624ff56 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSessionFactory.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSessionFactory.java @@ -3,5 +3,7 @@ package p.studio.api.session; import p.studio.api.project.ProjectReference; public interface ProjectSessionFactory { + /** Interactive product slice; implementations may defer agent and editor infrastructure. */ + default ProjectSession openForPlay(p.studio.api.project.ProjectReference project){return open(project);} ProjectSession open(ProjectReference projectReference); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java index c837946f..5811abfc 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java @@ -27,6 +27,12 @@ public final class DefaultExecutionControllerFactory implements ExecutionControl @Override public ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session) { + return create(project,setup,session,p.studio.api.execution.PlayOptions.PERSISTENT); + } + + @Override public ExecutionController create(ProjectReference project,ProjectLocalStudioSetup setup,ExecutionSession session,p.studio.api.execution.PlayOptions options) { + if(runtime.interactive())return new InteractiveExecutionController(project,setup,session,shipper,runtime,operations,access,options); + if(options.disposableSave())throw new UnsupportedOperationException("Disposable Play requires interactive host"); return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations, access); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionSession.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionSession.java index 34c14b36..045b4df1 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionSession.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionSession.java @@ -50,6 +50,11 @@ public final class DefaultExecutionSession implements ExecutionSession { @Override public void transitionToRunning() { publish(transitionLocked(ExecutionState.RUNNING, false)); } + @Override public void transitionToPausing() {publish(transitionLocked(ExecutionState.PAUSING,false));} + @Override public void transitionToPaused() {publish(transitionLocked(ExecutionState.PAUSED,false));} + @Override public void transitionToResuming() {publish(transitionLocked(ExecutionState.RESUMING,false));} + @Override public void transitionToStopping() {publish(transitionLocked(ExecutionState.STOPPING,false));} + @Override public void transitionToRuntimeFailed() { publish(transitionLocked(ExecutionState.RUNTIME_FAILED, false)); } @@ -92,7 +97,8 @@ public final class DefaultExecutionSession implements ExecutionSession { final ExecutionState current = snapshot().state(); if (current == ExecutionState.PREPARING || current == ExecutionState.CONNECTING - || current == ExecutionState.RUNNING) { + || current == ExecutionState.RUNNING || current == ExecutionState.PAUSING + || current == ExecutionState.PAUSED || current == ExecutionState.RESUMING || current == ExecutionState.STOPPING) { transitionToStopped(); } listeners.clear(); @@ -101,7 +107,9 @@ public final class DefaultExecutionSession implements ExecutionSession { private void appendLog(ExecutionLogSource source, ExecutionLogSeverity severity, String message, Instant timestamp) { final ExecutionSnapshot snapshot; synchronized (monitor) { - logs.add(new ExecutionLogEntry(nextSequence++, timestamp, source, severity, message)); + if(logs.size()==2048)logs.remove(0); + String bounded=message.length()>8192?message.substring(0,8192)+"…":message; + logs.add(new ExecutionLogEntry(nextSequence++, timestamp, source, severity, bounded)); snapshot = snapshotLocked(); } publish(snapshot); @@ -131,10 +139,15 @@ public final class DefaultExecutionSession implements ExecutionSession { case IDLE -> next == ExecutionState.PREPARING; case PREPARING -> next == ExecutionState.PREPARE_FAILED || next == ExecutionState.CONNECTING + || next == ExecutionState.STOPPING || next == ExecutionState.STOPPED; case PREPARE_FAILED -> next == ExecutionState.IDLE || next == ExecutionState.PREPARING; - case CONNECTING -> next == ExecutionState.RUNNING || next == ExecutionState.RUNTIME_FAILED || next == ExecutionState.STOPPED; - case RUNNING -> next == ExecutionState.STOPPED || next == ExecutionState.RUNTIME_FAILED; + case CONNECTING -> next == ExecutionState.RUNNING || next == ExecutionState.PAUSED || next == ExecutionState.STOPPING || next == ExecutionState.RUNTIME_FAILED || next == ExecutionState.STOPPED; + case RUNNING -> next == ExecutionState.PAUSING || next == ExecutionState.STOPPING || next == ExecutionState.STOPPED || next == ExecutionState.RUNTIME_FAILED; + case PAUSING -> next == ExecutionState.PAUSED || next == ExecutionState.RUNNING || next == ExecutionState.STOPPING || next == ExecutionState.STOPPED || next == ExecutionState.RUNTIME_FAILED; + case PAUSED -> next == ExecutionState.RESUMING || next == ExecutionState.STOPPING || next == ExecutionState.STOPPED || next == ExecutionState.RUNTIME_FAILED; + case RESUMING -> next == ExecutionState.RUNNING || next == ExecutionState.PAUSED || next == ExecutionState.STOPPING || next == ExecutionState.STOPPED || next == ExecutionState.RUNTIME_FAILED; + case STOPPING -> next == ExecutionState.STOPPED || next == ExecutionState.PAUSED || next == ExecutionState.RUNTIME_FAILED; case RUNTIME_FAILED, STOPPED -> next == ExecutionState.IDLE || next == ExecutionState.PREPARING; }; if (!allowed) throw new IllegalStateException("illegal execution transition: " + current + " -> " + next); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/InteractiveExecutionController.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/InteractiveExecutionController.java new file mode 100644 index 00000000..02322794 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/InteractiveExecutionController.java @@ -0,0 +1,174 @@ +package p.studio.core.execution; + +import p.studio.api.execution.*; +import p.studio.api.project.*; +import p.studio.api.operation.*; +import p.studio.api.automation.*; +import p.studio.api.shipper.*; +import p.studio.core.runtime.*; +import java.util.concurrent.*; + +/** Interactive session lifecycle. Process completion, rather than a click, releases authority. */ +final class InteractiveExecutionController implements ExecutionController { + private final Object monitor=new Object(); + private final ProjectReference project; + private final ProjectLocalStudioSetup setup; + private final ExecutionSession session; + private final Shipper shipper; + private final RuntimeGateway runtime; + private final OperationExecutor operations; + private final ProjectAccess access; + private final PlayOptions options; + private Attempt attempt; + private boolean closed; + private static final class Attempt { + final ManualLease lease; + volatile RuntimeConnection connection; + volatile OperationHandle play; + volatile OperationHandle preparation; + volatile boolean stopping,pauseOnReady; + boolean released; + CompletableFuture stop; + Attempt(ManualLease lease){this.lease=lease;} + } + InteractiveExecutionController(ProjectReference project,ProjectLocalStudioSetup setup,ExecutionSession session, + Shipper shipper,RuntimeGateway runtime,OperationExecutor operations,ProjectAccess access,PlayOptions options) { + this.project=project;this.setup=setup;this.session=session;this.shipper=shipper; + this.runtime=runtime;this.operations=operations;this.access=access;this.options=options; + } + @Override public OperationHandle play() { + synchronized(monitor){ + if(closed)throw new IllegalStateException("Execution controller is closed"); + if(attempt!=null&&!attempt.released){ + if(attempt.play!=null)return attempt.play; + throw new ControlDeniedException(ControlResult.Status.BUSY); + } + Attempt a=new Attempt(access.enterExecution(project.rootPath()));attempt=a; + a.lease.onProjectClose(()->stopAttempt(a));session.beginPreparationCycle(); + try{a.play=operations.submit("Play "+project.name(),()->start(a)); + a.play.termination().whenComplete((v,f)->{synchronized(monitor){ + if(a.connection==null){if(a.stopping)stoppedWithoutProcess(a);release(a);} + }}); + return a.play;} + catch(RuntimeException failure){release(a);session.transitionToPrepareFailed();throw failure;} + } + } + private ExecutionSnapshot start(Attempt a) { + try { + if(a.stopping)return session.snapshot(); + a.preparation=access.prepareExecution(project.rootPath(),()->shipper.prepare(project,session::appendShipperLog)); + if(a.stopping)a.preparation.cancel(); + ShipperPrepareResult prepared=a.preparation.completion().toCompletableFuture().join(); + a.preparation.termination().toCompletableFuture().join(); + if(a.stopping)return session.snapshot(); + if(!prepared.success()){session.transitionToPrepareFailed();return session.snapshot();} + session.transitionToConnecting(); + RuntimeConnection connection=runtime.start(project,setup, + log->session.appendRuntimeLog(log.severity(),log.message(),log.timestamp()),options); + synchronized(monitor){a.connection=connection;} + connection.completion().whenComplete((code,failure)->exited(a,connection,code,failure)); + if(a.stopping){connection.stopAsync().join();return session.snapshot();} + boolean paused=a.pauseOnReady; + if(paused)connection.pause().join(); + connection.startExecution().join(); + synchronized(monitor){ + if(attempt==a&&a.connection==connection&&!a.stopping){ + if(paused)session.transitionToPaused();else session.transitionToRunning(); + } + } + if(a.pauseOnReady&&!paused&&!a.stopping)pause(); + } catch(Throwable failure){ + Throwable cause=cause(failure); + synchronized(monitor){ + if(attempt==a&&a.connection==null){ + if(a.stopping){/* Actual worker termination owns the final state and lease. */} + else {log("Play failed: "+message(cause)); + if(session.snapshot().state()==ExecutionState.PREPARING)session.transitionToPrepareFailed(); + else session.transitionToRuntimeFailed();} + } else if(attempt==a&&!a.stopping){log("Runtime startup failed: "+message(cause));session.transitionToRuntimeFailed();} + } + } finally { + OperationHandle preparation=a.preparation; + if(preparation!=null)try{preparation.termination().toCompletableFuture().join();}catch(CompletionException|CancellationException ignored){} + a.preparation=null; + } + return session.snapshot(); + } + @Override public OperationHandle pause(){return changePause(true);} + @Override public OperationHandle resume(){return changePause(false);} + private OperationHandle changePause(boolean pause) { + synchronized(monitor){ + Attempt a=attempt; + if(a==null||a.released||a.stopping)throw new IllegalStateException("No controllable runtime"); + if(pause&&(session.snapshot().state()==ExecutionState.PREPARING||session.snapshot().state()==ExecutionState.CONNECTING)){ + a.pauseOnReady=true;return operations.submit("Pause on ready",session::snapshot); + } + ExecutionState expected=pause?ExecutionState.RUNNING:ExecutionState.PAUSED; + if(session.snapshot().state()!=expected)throw new IllegalStateException("Invalid pause/resume state"); + RuntimeConnection connection=a.connection; + if(pause)session.transitionToPausing();else session.transitionToResuming(); + return operations.submit(pause?"Pause":"Resume",()->{ + try{(pause?connection.pause():connection.resume()).join(); + synchronized(monitor){if(attempt==a&&a.connection==connection&&!a.stopping){ + if(pause)session.transitionToPaused();else session.transitionToRunning();}} + }catch(Throwable failure){synchronized(monitor){ + if(attempt==a&&a.connection==connection&&!a.stopping){ + log("Runtime control failed: "+message(cause(failure))); + if(pause)session.transitionToRunning();else session.transitionToPaused();}} + throw new CompletionException(cause(failure));} + return session.snapshot(); + }); + } + } + @Override public void stop(){stopAsync();} + @Override public CompletionStage stopAsync(){synchronized(monitor){return attempt==null?CompletableFuture.completedFuture(null):stopAttempt(attempt);}} + private CompletableFuture stopAttempt(Attempt a) { + synchronized(monitor){ + if(a.released)return CompletableFuture.completedFuture(null); + if(a.stop!=null)return a.stop; + a.stopping=true;a.stop=new CompletableFuture<>();CompletableFuture result=a.stop; + if(a.preparation!=null)a.preparation.cancel(); + if(a.play!=null&&!a.play.termination().toCompletableFuture().isDone())a.play.cancel(); + if(attempt==a&&active(session.snapshot().state()))session.transitionToStopping(); + try {operations.submit("Stop runtime",()->{ + try { + if(a.play!=null)try{a.play.termination().toCompletableFuture().join();}catch(CompletionException|CancellationException ignored){} + RuntimeConnection connection=a.connection; + if(connection!=null){connection.stopAsync().join();exited(a,connection,connection.completion().join(),null);} + synchronized(monitor){if(a.connection==null){stoppedWithoutProcess(a);release(a);} } + result.complete(null); + }catch(Throwable failure){Throwable why=cause(failure);synchronized(monitor){ + if(attempt==a&&why instanceof RuntimeStopRefusedException){ + a.stopping=false;a.stop=null;session.transitionToPaused(); + }else if(attempt==a&&!a.released){session.transitionToRuntimeFailed();} + log("Stop failed: "+message(why));} + result.completeExceptionally(why); + }return null; + });}catch(RuntimeException failure){result.completeExceptionally(failure);} + return result; + } + } + private void exited(Attempt a,RuntimeConnection connection,Integer code,Throwable failure){ + synchronized(monitor){ + if(a.connection!=connection)return;a.connection=null; + if(attempt==a){ + if(failure==null&&code!=null&&code==0)session.transitionToStopped(); + else {log("Runtime ended: "+(failure==null?"exit "+code:message(cause(failure))));session.transitionToRuntimeFailed();} + } + if(a.play==null||a.play.termination().toCompletableFuture().isDone())release(a); + else a.play.termination().whenComplete((v,f)->release(a)); + } + } + private void stoppedWithoutProcess(Attempt a){synchronized(monitor){ + if(attempt==a&&active(session.snapshot().state()))session.transitionToStopped();}} + private void release(Attempt a){synchronized(monitor){if(!a.released){a.released=true;a.lease.close();}}} + @Override public ExecutionFrame acquireLatestFrame(){synchronized(monitor){return attempt==null||attempt.connection==null?null:attempt.connection.acquireLatestFrame();}} + @Override public boolean ownsExecution(){synchronized(monitor){return attempt!=null&&!attempt.released;}} + @Override public void input(ExecutionInput input){synchronized(monitor){ + if(attempt!=null&&attempt.connection!=null&&session.snapshot().state()==ExecutionState.RUNNING)attempt.connection.input(input);}} + @Override public void close(){synchronized(monitor){closed=true;}stop();} + private void log(String text){session.appendRuntimeLog(ExecutionLogSeverity.ERROR,text);} + private static boolean active(ExecutionState state){return switch(state){case PREPARING,CONNECTING,RUNNING,PAUSING,PAUSED,RESUMING,STOPPING->true;default->false;};} + private static Throwable cause(Throwable failure){while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();return failure;} + private static String message(Throwable failure){return failure.getMessage()==null?failure.getClass().getSimpleName():failure.getMessage();} +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java index a09dc3d4..ebaa50cc 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java @@ -100,7 +100,8 @@ final class PlayStopExecutionController implements ExecutionController { } private ExecutionSnapshot runPlay() { - final OperationHandle preparation = shipper.prepare(project, session::appendShipperLog); + final OperationHandle preparation = access.prepareExecution(project.rootPath(), + () -> shipper.prepare(project, session::appendShipperLog)); synchronized (monitor) { preparationOperation = preparation; if (stopRequested) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java index 2998a0b7..e4285263 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java @@ -82,6 +82,7 @@ public final class ProjectAccessRegistry implements ProjectAccess { } if(automation.isEmpty())return enterManual(path); var session=automation.get(); + if(session instanceof p.studio.api.automation.ExecutionAuthority owner)return owner.enterExecution(); synchronized(session) { if(session.snapshot().manualOperations()!=0||session.runtimeAttached()) throw new p.studio.api.automation.ControlDeniedException(p.studio.api.automation.ControlResult.Status.BUSY); @@ -89,6 +90,28 @@ public final class ProjectAccessRegistry implements ProjectAccess { } } + @Override public T prepareExecution(Path path, java.util.function.Supplier work) { + java.util.Optional automation; + try {automation=findAutomation(path);} + catch(AutomationException failure){ + if(failure.failure().code()!=AutomationFailure.Code.PROJECT_NOT_OPEN)throw failure; + return work.get(); + } + if(automation.orElse(null) instanceof p.studio.api.automation.ExecutionAuthority owner) + return owner.prepareExecution(work); + return work.get(); + } + @Override public p.studio.api.operation.OperationHandle submitManual(Path path, + p.studio.api.operation.OperationExecutor executor,String summary,java.util.concurrent.Callable work) { + p.studio.api.automation.ExecutionAuthority owner=null; + try {if(findAutomation(path).orElse(null) instanceof p.studio.api.automation.ExecutionAuthority found)owner=found;} + catch(AutomationException failure){if(failure.failure().code()!=AutomationFailure.Code.PROJECT_NOT_OPEN)throw failure;} + var preparationOwner=owner; + java.util.concurrent.Callable admitted = owner!=null && owner.preparingExecution() + ? () -> preparationOwner.callExecutionPreparation(work) : work; + return ProjectAccess.super.submitManual(path,executor,summary,admitted); + } + private static Path canonical(Path path) { Path normalized = path.toAbsolutePath().normalize(); try { return normalized.toRealPath(); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeConnection.java b/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeConnection.java index a332a425..b8a6ff76 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeConnection.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeConnection.java @@ -5,6 +5,16 @@ import java.util.concurrent.CompletableFuture; public interface RuntimeConnection extends AutoCloseable { CompletableFuture completion(); + default CompletableFuture startExecution() { return CompletableFuture.completedFuture(null); } + default CompletableFuture pause() { return CompletableFuture.failedFuture(new UnsupportedOperationException("Pause unavailable")); } + default CompletableFuture resume() { return CompletableFuture.failedFuture(new UnsupportedOperationException("Resume unavailable")); } + default CompletableFuture stopAsync() { + try {close();return CompletableFuture.completedFuture(null);} + catch (RuntimeException failure) {return CompletableFuture.failedFuture(failure);} + } + default p.studio.api.execution.ExecutionFrame acquireLatestFrame() {return null;} + default void input(p.studio.api.execution.ExecutionInput input) { } + @Override void close(); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeGateway.java b/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeGateway.java index 3522c40e..fdc50e79 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeGateway.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeGateway.java @@ -9,4 +9,11 @@ import java.util.function.Consumer; public interface RuntimeGateway { RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup, Consumer logs) throws Exception; + + default boolean interactive() {return false;} + default RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup, + Consumer logs,p.studio.api.execution.PlayOptions options) throws Exception { + if(options.disposableSave())throw new UnsupportedOperationException("Disposable Play unavailable"); + return start(project,setup,logs); + } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeStopRefusedException.java b/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeStopRefusedException.java new file mode 100644 index 00000000..1172af62 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/runtime/RuntimeStopRefusedException.java @@ -0,0 +1,6 @@ +package p.studio.core.runtime; + +/** Normal Stop was refused to preserve pending/unsaved game data. The connection stays alive. */ +public final class RuntimeStopRefusedException extends RuntimeException { + public RuntimeStopRefusedException(String message) {super(message);} +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java index 5e5664f6..a6b3a90a 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java @@ -8,7 +8,7 @@ import java.util.concurrent.*; import java.util.function.Consumer; /** Project authority is independent of any UI, transport connection or operation result. */ -public final class DefaultAutomationSession implements AutomationSession { +public final class DefaultAutomationSession implements AutomationSession,ExecutionAuthority { private final Path root; private final OperationExecutor executor; private final AutomationConnectionLifecycle connections; @@ -20,6 +20,8 @@ public final class DefaultAutomationSession implements AutomationSession { private ControlState state = ControlState.MANUAL; private TaskIdentity task; private int manualOperations; + private boolean executionOwned; + private final ThreadLocal executionPreparation = ThreadLocal.withInitial(() -> false); private boolean handoffPending, closed, busy, stale; private long generation; private OperationHandle active; @@ -52,8 +54,12 @@ public final class DefaultAutomationSession implements AutomationSession { } public synchronized ManualLease enterManual() { + return enterManual(false); + } + private ManualLease enterManual(boolean executionAdmission) { if (closed) throw new ControlDeniedException(ControlResult.Status.CLOSED); if (state != ControlState.MANUAL) throw new ControlDeniedException(ControlResult.Status.BUSY); + if (executionOwned && !executionAdmission && !executionPreparation.get()) throw new ControlDeniedException(ControlResult.Status.BUSY); if (manualOperations++ == 0) manualIdle = new CompletableFuture<>(); stale = capture != null; publish(); @@ -82,6 +88,35 @@ public final class DefaultAutomationSession implements AutomationSession { }; } + /** One exclusive interactive owner; its preparation may temporarily enter the manual lane. */ + public synchronized ManualLease enterExecution() { + if (executionOwned || manualOperations!=0 || runtime!=null) + throw new ControlDeniedException(ControlResult.Status.BUSY); + executionOwned=true; + final ManualLease lease; + try {lease=enterManual(true);}catch(RuntimeException failure){executionOwned=false;throw failure;} + return new ManualLease() { + private boolean released; + @Override public void onProjectClose(Runnable action){lease.onProjectClose(action);} + @Override public void close(){synchronized(DefaultAutomationSession.this){ + if(!released){released=true;executionOwned=false;lease.close();} + }} + }; + } + public boolean preparingExecution(){return executionPreparation.get();} + public T prepareExecution(java.util.function.Supplier work) { + boolean prior=executionPreparation.get(); + synchronized(this){if(!executionOwned || closed)throw new ControlDeniedException(ControlResult.Status.BUSY);} + executionPreparation.set(true); + try{return work.get();}finally{if(prior)executionPreparation.set(true);else executionPreparation.remove();} + } + public T callExecutionPreparation(java.util.concurrent.Callable work) throws Exception { + boolean prior=executionPreparation.get(); + synchronized(this){if(!executionOwned || closed)throw new ControlDeniedException(ControlResult.Status.BUSY);} + executionPreparation.set(true); + try{return work.call();}finally{if(prior)executionPreparation.set(true);else executionPreparation.remove();} + } + @Override public synchronized AutomationSnapshot snapshot() { return new AutomationSnapshot(root, state, handoffPending, closed, manualOperations, task, active == null ? null : active.snapshot(), capture, stale, diagnostics, List.copyOf(calls), diagnosticResult, diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index 26a1ef2a..96cd4493 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -56,20 +56,28 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory @Override public synchronized ProjectSession open(ProjectReference projectReference) { + return open(projectReference,true); + } + @Override public synchronized ProjectSession openForPlay(ProjectReference projectReference){return open(projectReference,false);} + + private ProjectSession open(ProjectReference projectReference,boolean editorInfrastructure) { if (closed) throw new IllegalStateException("Project sessions are closing"); final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference"); final var setup = setupStore.load(project); // Preparation reports readiness independently; opening never grants agent authority. - if (setup.agentIntegration().enabled()) preparation.prepare(project.rootPath()); + if (editorInfrastructure && setup.agentIntegration().enabled()) preparation.prepare(project.rootPath()); + LspLifecyclePort lifecycle=editorInfrastructure?lsp:new LspLifecyclePort(){ + public void boot(ProjectReference ignored){}public void shutdown(ProjectReference ignored){} + }; final var state = stateStore.load(project); var automation = new DefaultAutomationSession(project.rootPath(), operations, connections); var ready = new java.util.concurrent.atomic.AtomicBoolean(); var registration = access.register(project.rootPath(), automation::enterManual, () -> ready.get() && !automation.snapshot().closed(), automation); - try { lsp.boot(project); } + try { lifecycle.boot(project); } catch (RuntimeException failure) { registration.unsubscribe(); throw failure; } ready.set(true); - var session = new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, () -> { + var session = new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lifecycle, state, automation, () -> { registration.unsubscribe(); synchronized (DefaultProjectSessionFactory.this) { sessions.removeIf(s -> s.automation() == automation); } }); diff --git a/prometeu-studio-core/src/test/java/p/studio/core/execution/InteractiveExecutionControllerTest.java b/prometeu-studio-core/src/test/java/p/studio/core/execution/InteractiveExecutionControllerTest.java new file mode 100644 index 00000000..59040861 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/execution/InteractiveExecutionControllerTest.java @@ -0,0 +1,103 @@ +package p.studio.core.execution; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.execution.*; +import p.studio.api.project.*; +import p.studio.api.operation.*; +import p.studio.api.shipper.*; +import p.studio.core.runtime.*; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.core.support.ControlledOperations; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +class InteractiveExecutionControllerTest { + @TempDir Path root; + static final class Connection implements RuntimeConnection { + final CompletableFuture exit=new CompletableFuture<>(); + final List commands=new CopyOnWriteArrayList<>();boolean refuse; + public CompletableFuture completion(){return exit;} + public CompletableFuture startExecution(){commands.add("start");return CompletableFuture.completedFuture(null);} + public CompletableFuture pause(){commands.add("pause");return CompletableFuture.completedFuture(null);} + public CompletableFuture resume(){commands.add("resume");return CompletableFuture.completedFuture(null);} + public CompletableFuture stopAsync(){ + if(refuse)return CompletableFuture.failedFuture(new RuntimeStopRefusedException("Save first")); + exit.complete(0);return CompletableFuture.completedFuture(null); + } + public void close(){stopAsync().join();} + } + private static OperationHandle done(T value){ + var operations=new ControlledOperations();var h=operations.submit("done",()->value);operations.last.finish();return h; + } + private Shipper shipper(){return (p,l)->done(new ShipperPrepareResult(ShipperPreparationStatus.SUCCESS,List.of(),root.resolve("manifest.json"),List.of(),List.of()));} + private RuntimeGateway gateway(Connection connection){return (p,s,l)->connection;} + private ProjectReference project(){return new ProjectReference("Game","1","pbs",1,ProjectTarget.Game,root);} + + @Test void failedConnectionReleasesAuthorityAfterCompletionAndAllowsAnotherAttempt(){ + var ops=new ControlledOperations();var authority=new DefaultAutomationSession(root,ops); + var access=new ProjectAccessRegistry();access.register(root,authority::enterManual,()->true,authority); + var state=new DefaultExecutionSession();var first=new Connection();var second=new Connection(); + var calls=new java.util.concurrent.atomic.AtomicInteger();RuntimeGateway runtime=(p,s,l)->calls.getAndIncrement()==0?first:second; + var controller=new InteractiveExecutionController(project(),ProjectLocalStudioSetup.defaults(),state,shipper(),runtime,ops,access,PlayOptions.PERSISTENT); + controller.play();ops.last.finish();assertTrue(controller.ownsExecution()); + first.exit.completeExceptionally(new java.io.IOException("video disconnected")); + assertEquals(ExecutionState.RUNTIME_FAILED,state.snapshot().state());assertFalse(controller.ownsExecution()); + try(var lease=access.enterManual(root)){} + assertTrue(state.snapshot().logs().stream().anyMatch(log->log.message().contains("video disconnected"))); + controller.play();ops.last.finish();assertEquals(ExecutionState.RUNNING,state.snapshot().state()); + var stopped=controller.stopAsync();ops.last.finish();stopped.toCompletableFuture().join();assertFalse(controller.ownsExecution()); + } + + @Test void pauseAndRefusedStopRetainOwnershipUntilProcessActuallyEnds(){ + var ops=new ControlledOperations();var authority=new DefaultAutomationSession(root,ops); + var access=new ProjectAccessRegistry();access.register(root,authority::enterManual,()->true,authority); + var state=new DefaultExecutionSession();var connection=new Connection(); + var controller=new InteractiveExecutionController(project(),ProjectLocalStudioSetup.defaults(),state,shipper(),gateway(connection),ops,access,PlayOptions.PERSISTENT); + controller.play();ops.last.finish();assertEquals(ExecutionState.RUNNING,state.snapshot().state()); + controller.pause();ops.last.finish();assertEquals(ExecutionState.PAUSED,state.snapshot().state()); + assertThrows(p.studio.api.automation.ControlDeniedException.class,()->access.enterManual(root)); + controller.resume();ops.last.finish();assertEquals(ExecutionState.RUNNING,state.snapshot().state()); + connection.refuse=true;var refused=controller.stopAsync();ops.last.finish(); + assertThrows(CompletionException.class,()->refused.toCompletableFuture().join()); + assertEquals(ExecutionState.PAUSED,state.snapshot().state());assertFalse(connection.exit.isDone()); + assertThrows(p.studio.api.automation.ControlDeniedException.class,()->access.enterManual(root)); + connection.refuse=false;var stop=controller.stopAsync();ops.last.finish();stop.toCompletableFuture().join(); + assertEquals(ExecutionState.STOPPED,state.snapshot().state()); + try(var edit=access.enterManual(root)){assertEquals(1,authority.snapshot().manualOperations());} + } + @Test void focusLostDuringStartupPausesBeforeArmingTheGame()throws Exception { + var ops=new ControlledOperations();var state=new DefaultExecutionSession();var connection=new Connection(); + var entered=new CountDownLatch(1);var proceed=new CountDownLatch(1); + RuntimeGateway gateway=(p,s,l)->{entered.countDown();assertTrue(proceed.await(2,TimeUnit.SECONDS));return connection;}; + var controller=new InteractiveExecutionController(project(),ProjectLocalStudioSetup.defaults(),state,shipper(),gateway,ops,new ProjectAccessRegistry(),PlayOptions.PERSISTENT); + controller.play();var play=ops.last;var running=CompletableFuture.runAsync(play::finish); + assertTrue(entered.await(2,TimeUnit.SECONDS));controller.pause();var pause=ops.last; + proceed.countDown();running.get(2,TimeUnit.SECONDS);pause.finish(); + assertEquals(List.of("pause","start"),connection.commands);assertEquals(ExecutionState.PAUSED,state.snapshot().state()); + var stopped=controller.stopAsync();ops.last.finish();stopped.toCompletableFuture().join(); + } + @Test void cancelledPreparationKeepsOwnershipUntilWriterActuallyTerminates()throws Exception { + var ops=new ControlledOperations();var prepOps=new ControlledOperations();var authority=new DefaultAutomationSession(root,ops); + var access=new ProjectAccessRegistry();access.register(root,authority::enterManual,()->true,authority); + var entered=new CountDownLatch(1);var state=new DefaultExecutionSession(); + Shipper preparation=(p,l)->{ + var h=access.submitManual(root,prepOps,"prepare",()->new ShipperPrepareResult( + ShipperPreparationStatus.SUCCESS,List.of(),root.resolve("manifest.json"),List.of(),List.of())); + entered.countDown();return h; + }; + RuntimeGateway runtime=(p,s,l)->{throw new AssertionError("Cancelled preparation must not start runtime");}; + var controller=new InteractiveExecutionController(project(),ProjectLocalStudioSetup.defaults(),state,preparation,runtime,ops,access,PlayOptions.PERSISTENT); + controller.play();var play=ops.last;var running=CompletableFuture.runAsync(play::finish); + assertTrue(entered.await(2,TimeUnit.SECONDS));var stop=controller.stopAsync();var stopper=ops.last; + prepOps.last.completed.completeExceptionally(new CancellationException()); + assertThrows(p.studio.api.automation.ControlDeniedException.class,()->access.enterManual(root)); + assertFalse(running.isDone());assertEquals(ExecutionState.STOPPING,state.snapshot().state()); + prepOps.last.finish();running.get(2,TimeUnit.SECONDS);stopper.finish();stop.toCompletableFuture().join(); + assertEquals(ExecutionState.STOPPED,state.snapshot().state()); + try(var editing=access.enterManual(root)){assertEquals(1,authority.snapshot().manualOperations());} + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java index 88861ed8..041f6260 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java @@ -17,6 +17,23 @@ class DefaultAutomationSessionTest { DefaultAutomationSession session() { return new DefaultAutomationSession(root, operations); } ControlResult await(CompletionStage result) { return result.toCompletableFuture().join(); } TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); } + @Test void interactiveOwnerBlocksOtherWritersButAdmitsItsPreparationAcrossThreads() throws Exception { + var s=session();var access=new ProjectAccessRegistry();access.register(root,s::enterManual,()->true,s); + try(var execution=access.enterExecution(root)){ + assertThrows(ControlDeniedException.class,s::enterManual); + assertThrows(ControlDeniedException.class,()->access.enterManual(root)); + assertEquals(BUSY,await(s.grant(false)).status()); + var prepared=access.prepareExecution(root,()->access.submitManual(root,operations,"prepare",()->{ + try(var nested=access.enterManual(root)){return "prepared";} + })); + assertThrows(ControlDeniedException.class,()->access.enterManual(root)); + CompletableFuture.runAsync(operations.last::finish).get(2,TimeUnit.SECONDS); + assertEquals("prepared",prepared.completion().toCompletableFuture().join()); + assertEquals(1,s.snapshot().manualOperations()); + } + try(var edit=access.enterManual(root)){assertEquals(1,s.snapshot().manualOperations());} + assertEquals(0,s.snapshot().manualOperations()); + } @Test void manualTestRuntimeUsesExistingLeaseAndPreventsGrantUntilExplicitCleanup() { var s=session();var runtime=new ManagedHeadlessSession(){public String sessionId(){return "manual-test";}public void cancel(){}public CompletionStage shutdown(){return CompletableFuture.completedFuture(null);}}; assertThrows(ControlDeniedException.class,()->s.attachRuntime(null,runtime)); diff --git a/prometeu-studio-ui-javafx-2/README.md b/prometeu-studio-ui-javafx-2/README.md index c48cc491..0956b630 100644 --- a/prometeu-studio-ui-javafx-2/README.md +++ b/prometeu-studio-ui-javafx-2/README.md @@ -1,8 +1,12 @@ # Studio JavaFX 2 foundation -This independent frontend contains the Studio presentation foundation and a minimal native-decorated shell. It has no dependency on the previous frontend, Studio services, MCP, a game project or the runtime. The previous application's launcher remains unchanged. +This frontend provides the Studio presentation foundation, project chooser and +integrated Play view used by the normal `prometeu-app` entry point. It consumes +neutral Studio API services and has no dependency on the previous frontend, Core, +concrete runtime/provider adapters or MCP. The standalone shell/gallery remain +independent developer demonstrations without a project/backend. -Requires Java 21 or later; Gradle selects Java 21 and JavaFX 23.0.2 for the module. +Requires Java 25; Gradle selects Java 25 and JavaFX 23.0.2 for the module. From the Studio repository: @@ -11,7 +15,10 @@ From the Studio repository: ./gradlew :prometeu-studio-ui-javafx-2:gallery ``` -The default shell contains identity, theme and language selectors and an empty central area. The **separate development gallery** demonstrates components, validation, progress, both fonts and configurable text scale. Its actions operate on sample text only. +The standalone shell contains identity, presentation selectors and an empty central +area. The application mounts its chooser/Play view in that shell. The **separate +development gallery** demonstrates components, validation, progress, both fonts and +configurable text scale. Gallery actions operate on sample text only. ```sh ./gradlew :prometeu-studio-ui-javafx-2:test diff --git a/prometeu-studio-ui-javafx-2/build.gradle.kts b/prometeu-studio-ui-javafx-2/build.gradle.kts index e802d887..b36fa07d 100644 --- a/prometeu-studio-ui-javafx-2/build.gradle.kts +++ b/prometeu-studio-ui-javafx-2/build.gradle.kts @@ -12,6 +12,8 @@ application { mainClass = "p.studio.ui.javafx2.StudioLauncher" } +dependencies { implementation(project(":prometeu-studio-api")) } + distributions { main { contents { diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java index 3d3e794a..15255033 100644 --- a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java @@ -15,7 +15,7 @@ public final class ComponentGallery extends VBox { var typeface = new StudioSelect<>(context,"font.label",Typeface::family,Typeface.values()); typeface.setId("font-select"); typeface.connect(() -> context.settings().typeface(), value -> context.update(context.settings().withTypeface(value))); var scale = new StudioSelect<>(context,"scale.label",value -> context.text("scale.value",value),.75,1.,1.25,1.5,2.); - scale.setId("scale-select"); scale.connect(() -> context.settings().scale(), value -> context.update(context.settings().withScale(value))); + scale.setId("gallery-scale-select"); scale.connect(() -> context.settings().scale(), value -> context.update(context.settings().withScale(value))); getChildren().add(new FlowPane(20,16,MinimalShell.labeled(context,"font.label",typeface),MinimalShell.labeled(context,"scale.label",scale))); StudioButton apply = new StudioButton(context,"action.apply",true); apply.setId("apply"); StudioButton reset = new StudioButton(context,"action.reset",false); reset.setId("reset"); diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/play/PlaybackViewport.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/play/PlaybackViewport.java new file mode 100644 index 00000000..bf9d7282 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/play/PlaybackViewport.java @@ -0,0 +1,78 @@ +package p.studio.ui.javafx2.play; + +import javafx.animation.AnimationTimer; +import javafx.scene.control.ScrollPane; +import javafx.scene.image.*; +import javafx.scene.input.*; +import javafx.scene.layout.*; +import p.studio.api.execution.*; +import java.util.*; +import java.util.function.Supplier; + +/** Logical-pixel viewport. Reception never waits for the JavaFX pulse. */ +public final class PlaybackViewport extends BorderPane implements AutoCloseable { + private final ImageView image=new ImageView(); + private final StackPane surface=new StackPane(image); + private final Supplier controller; + private final Supplier state; + private final EnumSet pressed=EnumSet.noneOf(KeyCode.class); + private final AnimationTimer timer; + private WritableImage writable; + private int zoom=1,width=480,height=270,touchX=-1,touchY=-1; + private boolean touching; + private long painted,lastFrame; + private final long[] latencies=new long[2048]; + private int latencyCount; + public PlaybackViewport(Supplier controller,Supplier state) { + this.controller=controller;this.state=state;setId("play-viewport"); + image.setId("game-image");image.setSmooth(false);image.setPreserveRatio(false); + surface.setId("game-surface");surface.setFocusTraversable(true);surface.setStyle("-fx-background-color: #080a0a;"); + ScrollPane scroll=new ScrollPane(surface);scroll.setFitToWidth(true);scroll.setFitToHeight(true);setCenter(scroll);resizeImage(); + surface.addEventFilter(KeyEvent.KEY_PRESSED,e->key(e,true)); + surface.addEventFilter(KeyEvent.KEY_RELEASED,e->key(e,false)); + surface.focusedProperty().addListener((o,a,b)->{if(!b)neutralize();}); + image.setOnMousePressed(e->{surface.requestFocus();touch(e,true);}); + image.setOnMouseDragged(e->touch(e,true)); + surface.addEventFilter(MouseEvent.MOUSE_RELEASED,e->{if(e.getButton()==MouseButton.PRIMARY)touch(e,false);}); + timer=new AnimationTimer(){@Override public void handle(long now){paint();}};timer.start(); + } + public void zoom(int value){if(value!=1&&value!=2&&value!=4)throw new IllegalArgumentException("Zoom");zoom=value;resizeImage();} + public int zoom(){return zoom;} + private void resizeImage(){image.setFitWidth(width*zoom);image.setFitHeight(height*zoom);surface.setMinSize(width*zoom,height*zoom);} + private void paint(){ + ExecutionController c=controller.get();if(c==null)return; + try(ExecutionFrame frame=c.acquireLatestFrame()){ + if(frame==null)return; + if(writable==null||width!=frame.width()||height!=frame.height()){ + width=frame.width();height=frame.height();writable=new WritableImage(width,height);image.setImage(writable);resizeImage(); + } + writable.getPixelWriter().setPixels(0,0,width,height,PixelFormat.getByteBgraPreInstance(),frame.pixels(),width*4); + lastFrame=frame.frameId();painted++;latencies[latencyCount++%latencies.length]=System.nanoTime()-frame.receivedAtNanos(); + } + } + private void key(KeyEvent event,boolean down){ + if(bit(event.getCode())<0)return; + if(event.isControlDown()||event.isMetaDown()||event.isAltDown()){neutralize();return;} + if(down&&state.get()!=ExecutionState.RUNNING)return; + if(down)pressed.add(event.getCode());else pressed.remove(event.getCode());send();event.consume(); + } + private static int bit(KeyCode code){return switch(code){ + case UP->0;case DOWN->1;case LEFT->2;case RIGHT->3;case A->4;case D->5;case W->6;case S->7; + case Q->8;case E->9;case Z->10;case SHIFT->11;default->-1;};} + private void touch(MouseEvent event,boolean down){ + if(down&&!event.isPrimaryButtonDown())return; + var p=image.sceneToLocal(event.getSceneX(),event.getSceneY()); + int x=(int)Math.floor(p.getX()/zoom),y=(int)Math.floor(p.getY()/zoom); + touching=down&&state.get()==ExecutionState.RUNNING&&x>=0&&y>=0&&x theme; @@ -20,8 +20,13 @@ public final class MinimalShell extends BorderPane { theme.setId("theme-select"); theme.connect(() -> context.settings().theme(), value -> context.update(context.settings().withTheme(value))); language = new StudioSelect<>(context,"language.label",StudioLanguage::label,StudioLanguage.values()); language.setId("language-select"); language.connect(() -> context.settings().language(), value -> context.update(context.settings().withLanguage(value))); + var typeface=new StudioSelect(context,"font.label",Typeface::family,Typeface.values()); + typeface.setId("typeface-select");typeface.connect(()->context.settings().typeface(),value->context.update(context.settings().withTypeface(value))); + var scale=new StudioSelect(context,"scale.label",value->context.text("scale.value",value),.75,1.0,1.25,1.5,2.0); + scale.setId("scale-select");scale.connect(()->context.settings().scale(),value->context.update(context.settings().withScale(value))); HBox identity = new HBox(12,new StudioIcon(),new StudioText(context,"brand").title()); identity.setAlignment(Pos.CENTER_LEFT); - FlowPane selectors = new FlowPane(18,14,labeled(context,"theme.label",theme),labeled(context,"language.label",language)); + FlowPane selectors = new FlowPane(18,14,labeled(context,"theme.label",theme),labeled(context,"language.label",language), + labeled(context,"font.label",typeface),labeled(context,"scale.label",scale)); selectors.setPrefWrapLength(680); PresentationToolbar toolbar = new PresentationToolbar(identity,selectors); setTop(toolbar); workspace.setId("empty-workspace"); workspace.getStyleClass().add("workspace"); diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/StudioWindowCoordinator2.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/StudioWindowCoordinator2.java new file mode 100644 index 00000000..1353e856 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/StudioWindowCoordinator2.java @@ -0,0 +1,226 @@ +package p.studio.ui.javafx2.window; + +import javafx.animation.AnimationTimer; +import javafx.application.Platform; +import javafx.geometry.Insets; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.*; +import javafx.stage.*; +import p.studio.api.execution.*; +import p.studio.api.project.*; +import p.studio.api.session.*; +import p.studio.ui.javafx2.appearance.AppearanceContext; +import p.studio.ui.javafx2.components.*; +import p.studio.ui.javafx2.play.PlaybackViewport; +import p.studio.ui.javafx2.shell.MinimalShell; +import java.nio.file.Path; +import java.util.concurrent.*; +import java.util.function.*; + +/** The normal Studio product: one project and one owned interactive execution. */ +public final class StudioWindowCoordinator2 implements AutoCloseable { + private final Stage stage; + private final ProjectCatalog catalog; + private final KnownProjects known; + private final ProjectSessionFactory sessions; + private final ExecutionControllerFactory executions; + private final BiConsumer saveSetup; + private final Executor executor; + private final WindowResources resources; + private final AppearanceContext context; + private AppearanceContext viewContext; + private final MinimalShell shell; + private final Label notice=new Label(); + private final AnimationTimer lifecycle; + private ProjectSession project; + private ExecutionController controller; + private PlaybackViewport viewport; + private VBox configuration; + private StudioTextField runtimePath,savePath; + private CheckBox disposable; + private Button play,pause,resume,stop,closeProject; + private Label stateLabel; + private TextArea logs; + private long lastLog=-1; + private long operationSequence; + private ExecutionState displayedState; + private boolean busy,closing,projectCloseRequested,exitRequested,closed,focusPauseArmed; + + public StudioWindowCoordinator2(Stage stage,ProjectCatalog catalog,KnownProjects known,ProjectSessionFactory sessions, + ExecutionControllerFactory executions,BiConsumer saveSetup, + Executor executor,WindowResources resources) { + this.stage=stage;this.catalog=catalog;this.known=known;this.sessions=sessions;this.executions=executions; + this.saveSetup=saveSetup;this.executor=executor;this.resources=resources; + context=resources.context();shell=new MinimalShell(context);notice.setWrapText(true);notice.setId("studio-notice"); + context.observe(()->shell.workspace().setAccessibleText(project==null?context.text("projects.title"):project.projectReference().name())); + shell.setBottom(notice);BorderPane.setMargin(notice,new Insets(10,18,12,18)); + stage.setScene(new Scene(shell,1200,850));stage.setTitle("Prometeu Studio");stage.setMinWidth(680);stage.setMinHeight(480); + stage.setOnCloseRequest(e->{e.consume();exitRequested=true;requestCloseProject();}); + stage.iconifiedProperty().addListener((o,a,b)->{if(b)pauseForFocus();}); + lifecycle=new AnimationTimer(){long previous;@Override public void handle(long now){ + if(now-previous<100_000_000)return;previous=now; + boolean ours=Window.getWindows().stream().anyMatch(w->w.isFocused()&&belongsToStudio(w)); + if(!ours)pauseForFocus();else focusPauseArmed=false; + refresh(); + }};lifecycle.start(); + } + public void showLauncher(){showChooser();stage.show();} + private boolean belongsToStudio(Window window){ + if(window==stage)return true; + if(window instanceof Stage s&&s.getOwner()!=null)return belongsToStudio(s.getOwner()); + return window instanceof PopupWindow p&&p.getOwnerWindow()!=null&&belongsToStudio(p.getOwnerWindow()); + } + private AppearanceContext beginView(){ + if(viewport!=null){viewport.close();viewport=null;} + if(viewContext!=null)viewContext.close();viewContext=resources.child(context);return viewContext; + } + private Button button(AppearanceContext c,String key,String id,Runnable action){ + Button b=new StudioButton(c,key,false);b.setId(id);b.setOnAction(e->safe(action));return b; + } + private void safe(Runnable action){try{action.run();}catch(RuntimeException failure){error(failure);}} + private void error(Throwable failure){while(failure instanceof CompletionException&&failure.getCause()!=null)failure=failure.getCause(); + notice.setText(failure.getMessage()==null?failure.getClass().getSimpleName():failure.getMessage());} + private void background(Supplier work,BiConsumer result){ + CompletableFuture.supplyAsync(work,executor).whenComplete((value,failure)->Platform.runLater(()->{if(!closed)result.accept(value,failure);})); + } + private void showChooser(){ + var c=beginView();shell.workspace().setAccessibleText(c.text("projects.title")); + VBox content=new VBox(14,new StudioText(c,"projects.title").title());content.setPadding(new Insets(20)); + content.getChildren().add(button(c,"projects.open","open-project",()->{ + DirectoryChooser chooser=new DirectoryChooser();chooser.setTitle(c.text("projects.open")); + var selected=chooser.showDialog(stage);if(selected!=null)openProject(selected.toPath()); + })); + VBox rows=new VBox(12);content.getChildren().add(rows); + ScrollPane scroll=new ScrollPane(content);scroll.setFitToWidth(true);shell.workspace().getChildren().setAll(scroll); + background(known::listKnownProjects,(list,failure)->{ + if(viewContext!=c||project!=null)return;if(failure!=null){error(failure);return;} + for(ProjectReference ref:list){ + Label title=new Label(ref.name()+"\n"+ref.rootPath());title.setWrapText(true);HBox.setHgrow(title,Priority.ALWAYS); + var row=new HBox(16,title,button(c,"projects.open","known-open",()->openProject(ref.rootPath())), + button(c,"projects.forget","known-forget",()->{ + if(busy)return;busy=true;background(()->{known.forget(ref);return true;},(v,f)->{ + busy=false;if(exitRequested)finishExit();else if(f!=null)error(f);else showChooser();}); + }));row.setPadding(new Insets(14));rows.getChildren().add(new StudioPanel(row)); + } + }); + } + public void openProject(Path path){ + if(busy||project!=null||closing)return;busy=true;notice.setText(context.text("feedback.busy")); + background(()->{var ref=catalog.openProject(path);var opened=sessions.openForPlay(ref); + try{known.remember(ref);return opened;}catch(RuntimeException f){opened.close();throw f;}},(opened,failure)->{ + busy=false;if(failure!=null){error(failure);projectCloseRequested=false;if(exitRequested)finishExit();return;} + project=opened;notice.setText("");showProject();if(exitRequested||projectCloseRequested)requestCloseProject(); + }); + } + private void showProject(){ + var c=beginView();var ref=project.projectReference();var setup=project.projectLocalStudioSetup(); + shell.workspace().setAccessibleText(ref.name()); + Label title=new Label(ref.name());title.getStyleClass().add("studio-title");HBox.setHgrow(title,Priority.ALWAYS); + closeProject=button(c,"projects.close","close-project",this::requestCloseProject); + HBox heading=new HBox(18,title,closeProject); + runtimePath=new StudioTextField();runtimePath.setId("runtime-path");runtimePath.setText(setup.prometeuRuntimePath()); + Button browseRuntime=button(c,"play.browse","runtime-browse",()->{ + DirectoryChooser chooser=new DirectoryChooser();var chosen=chooser.showDialog(stage);if(chosen!=null)runtimePath.setText(chosen.getAbsolutePath());}); + HBox runtimeRow=new HBox(12,runtimePath,browseRuntime);HBox.setHgrow(runtimePath,Priority.ALWAYS); + configuration=new VBox(8,MinimalShell.labeled(c,"play.runtime",runtimeRow)); + disposable=new CheckBox();c.bindText(disposable,"play.disposable");disposable.setId("disposable-save"); + savePath=new StudioTextField();savePath.setId("memcard-path");savePath.setText(setup.memcardPath()); + if(ref.memcardSlots()!=null){ + Button browseSave=button(c,"play.browse","memcard-browse",()->{ + FileChooser chooser=new FileChooser();var chosen=chooser.showOpenDialog(stage);if(chosen!=null){savePath.setText(chosen.getAbsolutePath());disposable.setSelected(false);}}); + HBox row=new HBox(12,savePath,browseSave);HBox.setHgrow(savePath,Priority.ALWAYS); + disposable.selectedProperty().addListener((o,a,b)->row.setDisable(b)); + configuration.getChildren().addAll(MinimalShell.labeled(c,"play.memcard",row),disposable); + } + play=button(c,"play.start","play",this::play); + pause=button(c,"play.pause","pause",()->{viewport.neutralize();observe(controller.pause().completion());}); + resume=button(c,"play.resume","resume",()->{observe(controller.resume().completion());viewport.focusGame();}); + stop=button(c,"play.stop","stop",()->{viewport.neutralize();observe(controller.stopAsync());}); + StudioSelect zoom=new StudioSelect<>(c,"play.zoom",n->"x"+n,1,2,4);zoom.setId("viewport-zoom");zoom.setValue(1); + viewport=new PlaybackViewport(()->controller,()->project.executionSession().snapshot().state()); + zoom.setOnAction(e->{if(zoom.getValue()!=null)viewport.zoom(zoom.getValue());}); + stateLabel=new Label();stateLabel.setId("execution-state"); + c.observe(()->{displayedState=null;refresh();}); + FlowPane controls=new FlowPane(12,10,play,pause,resume,stop,zoom,stateLabel); + logs=new TextArea();logs.setId("execution-logs");logs.setEditable(false);logs.setPrefRowCount(4);logs.setWrapText(true); + VBox top=new VBox(14,heading,configuration,controls);top.setPadding(new Insets(16)); + BorderPane body=new BorderPane(viewport,top,null,logs,null);body.setId("project-play"); + shell.workspace().getChildren().setAll(body);lastLog=-1;refresh(); + } + private void play(){ + if(busy||closing||controller!=null&&controller.ownsExecution())return; + var original=project.projectLocalStudioSetup();var ref=project.projectReference(); + String runtime=runtimePath.getText();if(runtime==null||runtime.isBlank())throw new IllegalArgumentException(context.text("play.runtime.required")); + boolean discard=ref.memcardSlots()!=null&&disposable.isSelected(); + if(ref.memcardSlots()!=null&&!discard&&(savePath.getText()==null||savePath.getText().isBlank())) + throw new IllegalArgumentException(context.text("play.memcard.required")); + var setup=new ProjectLocalStudioSetup(runtime,original.editorIndentation(),original.agentIntegration(),savePath.getText()); + busy=true;refresh();notice.setText(""); + background(()->{saveSetup.accept(ref,setup);return setup;},(saved,failure)->{ + busy=false;if(failure!=null){error(failure);if(exitRequested||projectCloseRequested)requestCloseProject();return;} + if(closing||exitRequested||projectCloseRequested){requestCloseProject();return;} + safe(()->{if(controller!=null)controller.close(); + controller=executions.create(ref,saved,project.executionSession(),new PlayOptions(discard)); + observe(controller.play().completion());viewport.focusGame(); + if(stage.isIconified()||!Window.getWindows().stream().anyMatch(w->w.isFocused()&&belongsToStudio(w)))pauseForFocus();refresh();}); + }); + } + private void observe(CompletionStage operation){ + ProjectSession originProject=project;ExecutionController originController=controller; + long command=++operationSequence; + operation.whenComplete((v,f)->Platform.runLater(()->{ + if(!closed&&project==originProject&&controller==originController&&command==operationSequence){ + if(f!=null)error(f);refresh(); + } + })); + } + private void pauseForFocus(){ + if(controller==null||project==null)return; + if(viewport!=null)viewport.neutralize(); + ExecutionState state=project.executionSession().snapshot().state(); + if(focusPauseArmed&&(state==ExecutionState.PREPARING||state==ExecutionState.CONNECTING))return; + if(state==ExecutionState.RUNNING||state==ExecutionState.PREPARING||state==ExecutionState.CONNECTING) + safe(()->{focusPauseArmed=true;observe(controller.pause().completion());}); + } + private void refresh(){ + if(project==null||play==null||closed)return; + var snapshot=project.executionSession().snapshot();var state=snapshot.state();boolean owned=controller!=null&&controller.ownsExecution(); + configuration.setDisable(busy||closing||owned);configuration.setVisible(!owned);configuration.setManaged(!owned); + play.setDisable(busy||closing||owned); + pause.setDisable(closing||state!=ExecutionState.RUNNING);resume.setDisable(closing||state!=ExecutionState.PAUSED); + stop.setDisable(closing||!owned||state==ExecutionState.STOPPING);closeProject.setDisable(closing); + if(displayedState!=state){displayedState=state;stateLabel.setText(viewContext.text("state."+state.name())); + if(state!=ExecutionState.RUNNING&&viewport!=null)viewport.neutralize();} + long sequence=snapshot.logs().isEmpty()?0:snapshot.logs().getLast().sequence(); + if(logs!=null&&lastLog!=sequence){lastLog=sequence;StringBuilder text=new StringBuilder(); + int start=Math.max(0,snapshot.logs().size()-300); + for(var entry:snapshot.logs().subList(start,snapshot.logs().size()))text.append(entry.severity()).append(" · ").append(entry.message()).append('\n'); + logs.setText(text.toString());logs.positionCaret(logs.getLength());} + } + public void requestCloseProject(){ + if(closed||closing)return; + projectCloseRequested=true; + if(busy){if(exitRequested)notice.setText(context.text("feedback.busy"));return;} + if(project==null){projectCloseRequested=false;if(exitRequested)finishExit();return;} + closing=true;refresh();if(viewport!=null)viewport.neutralize(); + CompletionStage stopping=controller==null?CompletableFuture.completedFuture(null):controller.stopAsync(); + stopping.whenComplete((v,f)->Platform.runLater(()->{ + if(f!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(f);refresh();return;} + var oldProject=project;var oldController=controller; + background(()->{if(oldController!=null)oldController.close();oldProject.close();return true;},(done,failure)->{ + if(failure!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(failure);refresh();return;} + project=null;controller=null;closing=false;projectCloseRequested=false;play=null;notice.setText(""); + if(exitRequested)finishExit();else showChooser(); + }); + })); + } + private void finishExit(){close();stage.hide();Platform.exit();} + public PlaybackViewport viewport(){return viewport;} + public ProjectSession projectSession(){return project;} + @Override public void close(){ + if(closed)return;closed=true;lifecycle.stop();if(viewport!=null)viewport.close(); + if(controller!=null)controller.close();if(project!=null)project.close(); + if(viewContext!=null)viewContext.close();context.close();resources.close();stage.setOnCloseRequest(null); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/WindowResources.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/WindowResources.java new file mode 100644 index 00000000..f6820cd0 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/window/WindowResources.java @@ -0,0 +1,29 @@ +package p.studio.ui.javafx2.window; + +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.i18n.Messages; +import p.studio.ui.javafx2.preferences.*; +import java.util.Locale; +import java.util.prefs.Preferences; + +/** Loaded before opening the window; preferences and font I/O stay off the FX thread. */ +public final class WindowResources implements AutoCloseable { + private final PresentationSettings initial; + private final FontResources fonts; + private final Messages messages; + private final SettingsPersistence persistence; + public WindowResources() { + var store=new UserSettingsStore(Preferences.userRoot().node("p/studio/ui/javafx2"),Locale.getDefault(),System.err::println); + initial=store.load();persistence=new SettingsPersistence(store); + fonts=FontResources.load(System.err::println);messages=Messages.load(System.err::println); + } + public AppearanceContext context(){return new AppearanceContext(initial,messages,fonts,persistence::changed);} + public AppearanceContext child(AppearanceContext parent){ + var child=new AppearanceContext(parent.settings(),messages,fonts,parent::update); + javafx.beans.value.ChangeListener listener=(o,a,b)->child.update(b); + parent.settingsProperty().addListener(listener); + child.onClose(()->parent.settingsProperty().removeListener(listener)); + return child; + } + @Override public void close(){persistence.close();} +} diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties index 9feeacb8..542d37ac 100644 --- a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties @@ -1,4 +1,30 @@ brand=prometeu studio +projects.title=PROJECTS +projects.open=Open project +projects.forget=Forget +projects.close=Close project +play.runtime=Runtime installation +play.browse=Browse… +play.memcard=Development save media +play.disposable=Disposable session · changes will not be saved +play.runtime.required=Choose a runtime installation before Play. +play.memcard.required=Select existing save media or explicitly choose a disposable session. +play.start=Play +play.pause=Pause +play.resume=Resume +play.stop=Stop +play.zoom=Zoom +state.IDLE=Ready +state.PREPARING=Preparing… +state.PREPARE_FAILED=Preparation failed +state.CONNECTING=Connecting… +state.RUNNING=Playing +state.PAUSING=Pausing… +state.PAUSED=Paused · Resume to continue +state.RESUMING=Resuming… +state.STOPPING=Stopping… +state.RUNTIME_FAILED=Runtime failed · see logs +state.STOPPED=Stopped theme.label=Theme theme.dark=Bananodore · dark theme.light=Bananodore · light diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties index 28311f82..9bd542b6 100644 --- a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties @@ -1,4 +1,30 @@ brand=prometeu studio +projects.title=PROJETOS +projects.open=Abrir projeto +projects.forget=Esquecer +projects.close=Fechar projeto +play.runtime=Instalação do runtime +play.browse=Procurar… +play.memcard=Mídia de save para desenvolvimento +play.disposable=Sessão descartável · alterações não serão salvas +play.runtime.required=Escolha uma instalação do runtime antes de jogar. +play.memcard.required=Selecione uma mídia de save existente ou escolha explicitamente uma sessão descartável. +play.start=Play +play.pause=Pause +play.resume=Resume +play.stop=Stop +play.zoom=Zoom +state.IDLE=Pronto +state.PREPARING=Preparando… +state.PREPARE_FAILED=Falha na preparação +state.CONNECTING=Conectando… +state.RUNNING=Jogando +state.PAUSING=Pausando… +state.PAUSED=Pausado · Resume para continuar +state.RESUMING=Retomando… +state.STOPPING=Encerrando… +state.RUNTIME_FAILED=Falha no runtime · consulte os logs +state.STOPPED=Encerrado theme.label=Tema theme.dark=Bananodore · escuro theme.light=Bananodore · claro diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java index 82ebd2e1..4095e229 100644 --- a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java @@ -26,6 +26,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; /** Opt-in real toolkit contract tests. No backend, game project, or personal preference writes. */ +@org.junit.jupiter.api.Tag("integration") class FoundationDesktopTest { private static FontResources fonts; private static Messages messages; diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java index 36597088..893dba12 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java @@ -100,6 +100,10 @@ public enum I18n { WORKSPACE_DEBUG_STATUS_PREPARE_FAILED("workspace.debug.status.prepareFailed"), WORKSPACE_DEBUG_STATUS_CONNECTING("workspace.debug.status.connecting"), WORKSPACE_DEBUG_STATUS_RUNNING("workspace.debug.status.running"), + WORKSPACE_DEBUG_STATUS_PAUSING("workspace.debug.status.pausing"), + WORKSPACE_DEBUG_STATUS_PAUSED("workspace.debug.status.paused"), + WORKSPACE_DEBUG_STATUS_RESUMING("workspace.debug.status.resuming"), + WORKSPACE_DEBUG_STATUS_STOPPING("workspace.debug.status.stopping"), WORKSPACE_DEBUG_STATUS_RUNTIME_FAILED("workspace.debug.status.runtimeFailed"), WORKSPACE_DEBUG_STATUS_STOPPED("workspace.debug.status.stopped"), diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/debug/DebugWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/debug/DebugWorkspace.java index 2a3ed3f6..0eaff985 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/debug/DebugWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/debug/DebugWorkspace.java @@ -114,6 +114,10 @@ public final class DebugWorkspace extends Workspace { case PREPARE_FAILED -> I18n.WORKSPACE_DEBUG_STATUS_PREPARE_FAILED; case CONNECTING -> I18n.WORKSPACE_DEBUG_STATUS_CONNECTING; case RUNNING -> I18n.WORKSPACE_DEBUG_STATUS_RUNNING; + case PAUSING -> I18n.WORKSPACE_DEBUG_STATUS_PAUSING; + case PAUSED -> I18n.WORKSPACE_DEBUG_STATUS_PAUSED; + case RESUMING -> I18n.WORKSPACE_DEBUG_STATUS_RESUMING; + case STOPPING -> I18n.WORKSPACE_DEBUG_STATUS_STOPPING; case RUNTIME_FAILED -> I18n.WORKSPACE_DEBUG_STATUS_RUNTIME_FAILED; case STOPPED -> I18n.WORKSPACE_DEBUG_STATUS_STOPPED; }; diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties index e6fb3613..ec431f75 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties @@ -80,6 +80,10 @@ workspace.debug.status.preparing=Preparing workspace.debug.status.prepareFailed=Preparation failed workspace.debug.status.connecting=Connecting workspace.debug.status.running=Running +workspace.debug.status.pausing=Pausing +workspace.debug.status.paused=Paused +workspace.debug.status.resuming=Resuming +workspace.debug.status.stopping=Stopping workspace.debug.status.runtimeFailed=Runtime failed workspace.debug.status.stopped=Stopped diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties index 185702e3..e4d07359 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties @@ -26,6 +26,10 @@ workspace.debug.status.preparing=Preparando workspace.debug.status.prepareFailed=Preparacao falhou workspace.debug.status.connecting=Conectando workspace.debug.status.running=Executando +workspace.debug.status.pausing=Pausando +workspace.debug.status.paused=Pausado +workspace.debug.status.resuming=Retomando +workspace.debug.status.stopping=Encerrando workspace.debug.status.runtimeFailed=Runtime falhou workspace.debug.status.stopped=Parado workspace.dev=DEV diff --git a/test-projects/main/assets/.prometeu/cache.json b/test-projects/main/assets/.prometeu/cache.json index 6b0c9b03..21c5ccc4 100644 --- a/test-projects/main/assets/.prometeu/cache.json +++ b/test-projects/main/assets/.prometeu/cache.json @@ -36,7 +36,9 @@ "category" : "STRUCTURAL", "message" : "Tile image exceeds color limit for flag01.png: expected at most 16 RGBA8888 colors", "evidence_path" : "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/test-projects/main/assets/Zelda3/flag01.png", - "blocking" : true + "blocking" : true, + "code" : null, + "context" : { } } ] }, { "relative_path" : "flag02.png", @@ -50,7 +52,9 @@ "category" : "STRUCTURAL", "message" : "Tile image exceeds color limit for flag02.png: expected at most 16 RGBA8888 colors", "evidence_path" : "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/test-projects/main/assets/Zelda3/flag02.png", - "blocking" : true + "blocking" : true, + "code" : null, + "context" : { } } ] }, { "relative_path" : "flag03.png", @@ -217,7 +221,9 @@ "category" : "STRUCTURAL", "message" : "Invalid glyph dimensions for t1381s1.png: expected 32x32 but got 320x208", "evidence_path" : "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/test-projects/main/assets/Zelda3/t1381s1.png", - "blocking" : true + "blocking" : true, + "code" : null, + "context" : { } } ] }, { "relative_path" : "t1489s1.png", @@ -231,13 +237,17 @@ "category" : "STRUCTURAL", "message" : "Invalid glyph dimensions for t1489s1.png: expected 32x32 but got 288x128", "evidence_path" : "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/test-projects/main/assets/Zelda3/t1489s1.png", - "blocking" : true + "blocking" : true, + "code" : null, + "context" : { } }, { "severity" : "ERROR", "category" : "STRUCTURAL", "message" : "Tile image exceeds color limit for t1489s1.png: expected at most 16 RGBA8888 colors", "evidence_path" : "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/test-projects/main/assets/Zelda3/t1489s1.png", - "blocking" : true + "blocking" : true, + "code" : null, + "context" : { } } ] } ] }, { diff --git a/tools/documentation/verify.py b/tools/documentation/verify.py deleted file mode 100644 index 179effae..00000000 --- a/tools/documentation/verify.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python3 -"""Check repository Markdown navigation without fetching or modifying sources. - -Runtime mirrors keep provider-relative links and exact bytes. Pass --runtime to -also check provider links against a local read-only checkout; otherwise those -references are reported separately and do not make ordinary builds depend on it. -""" -import argparse -import re -import subprocess -from pathlib import Path -from urllib.parse import unquote - - -def prose(text): - """Exclude fenced examples; their sample links are not document navigation.""" - lines = [] - fence = None - for line in text.splitlines(): - match = re.match(r"^\s{0,3}(`{3,}|~{3,})", line) - if match: - marker = match.group(1) - if fence is None: - fence = marker - elif marker[0] == fence[0] and len(marker) >= len(fence): - fence = None - lines.append("") - else: - lines.append(line if fence is None else "") - return "\n".join(lines) - - -def anchors(text): - found = set(re.findall(r'(?:id|name)=["\']([^"\']+)["\']', text)) - counts = {} - for heading in re.findall(r"^ {0,3}#{1,6}\s+(.+?)\s*#*\s*$", prose(text), re.M): - heading = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", heading) - heading = re.sub(r"<[^>]+>", "", heading).lower() - slug = re.sub(r"[^\w\-\s]", "", heading).replace(" ", "-") - count = counts.get(slug, 0) - counts[slug] = count + 1 - found.add(slug + (f"-{count}" if count else "")) - return found - - -def verify(root, runtime): - tracked = subprocess.check_output( - ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], - cwd=root, text=True).split("\0") - files = {root / name for name in tracked if name.endswith(".md")} - files.add(root / "AGENTS.md") - files = sorted(path for path in files if path.is_file()) - mirror_names = {"docs/vm-arch/ARCHITECTURE.md", "docs/vm-arch/ISA_CORE.md"} - failures = [] - local_count = provider_count = 0 - anchor_cache = {} - for source in files: - relative = source.relative_to(root).as_posix() - content = prose(source.read_text()) - links = re.findall(r"\]\(([^)\n]+)\)", content) - links += re.findall(r"^\s*\[[^\]]+\]:\s*(\S+)", content, re.M) - for link in links: - link = link.strip().strip("<>") - if re.match(r"[a-zA-Z][a-zA-Z\d+.-]*:", link) or link.startswith("//"): - continue - path, _, fragment = link.partition("#") - target = (source.parent / unquote(path)).resolve() if path else source - provider = False - if relative in mirror_names: - provider = True - if runtime: - target = ((runtime / relative).parent / unquote(path)).resolve() if path else runtime / relative - elif target.is_relative_to(root.parent / "runtime"): - provider = True - if runtime: - target = runtime / target.relative_to(root.parent / "runtime") - if provider: - provider_count += 1 - if runtime is None: - continue - else: - local_count += 1 - if not target.exists(): - failures.append(f"{relative}: missing target {link}") - elif fragment and target.suffix == ".md": - if target not in anchor_cache: - anchor_cache[target] = anchors(target.read_text()) - if unquote(fragment) not in anchor_cache[target]: - failures.append(f"{relative}: missing anchor {link}") - for failure in failures: - print(failure) - mode = "checked" if runtime else "classified; use --runtime to check" - print(f"Markdown: {len(files)} files; {local_count} local links; " - f"{provider_count} provider links ({mode}); {len(failures)} failures") - return bool(failures) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2]) - parser.add_argument("--runtime", type=Path) - args = parser.parse_args() - raise SystemExit(verify(args.root.resolve(), args.runtime.resolve() if args.runtime else None)) diff --git a/tools/pbs-production-corpus/PbsProductionCorpusProbe.java b/tools/pbs-production-corpus/PbsProductionCorpusProbe.java deleted file mode 100644 index dcc00e8c..00000000 --- a/tools/pbs-production-corpus/PbsProductionCorpusProbe.java +++ /dev/null @@ -1,138 +0,0 @@ -import com.fasterxml.jackson.databind.ObjectMapper; -import p.studio.compiler.FrontendRegistryService; -import p.studio.compiler.messages.BuildingIssue; -import p.studio.compiler.messages.BuilderPipelineConfig; -import p.studio.compiler.models.BuilderPipelineContext; -import p.studio.compiler.source.identifiers.FileId; -import p.studio.compiler.workspaces.BuilderPipelineService; -import p.studio.compiler.workspaces.PipelineStage; -import p.studio.compiler.workspaces.stages.*; -import p.studio.utilities.logs.LogAggregator; - -import java.nio.file.*; -import java.security.MessageDigest; -import java.util.*; - -/** Research-only probe: production stages, isolated source projects, no compiler changes. */ -public final class PbsProductionCorpusProbe { - static final ObjectMapper MAPPER = new ObjectMapper(); - static final String ANALYSIS_ID = UUID.randomUUID().toString(); - static int issueIndex; - static final List LOG = new ArrayList<>(); - - public static void main(String[] args) throws Exception { - Path root = Path.of(args[0]).toRealPath(); - boolean optimize = args[1].equals("optimized"); - boolean publicEntry = args.length > 3 && args[3].equals("public"); - var result = new LinkedHashMap(); - result.put("projectRoot", root.toString()); - result.put("optimization", optimize ? "optimized" : "unoptimized"); - result.put("entrypoint", publicEntry ? "BuilderPipelineService.compile" : "public analysis + production compile stages"); - result.put("frontendOrigin", FrontendRegistryService.require("pbs").getClass().getProtectionDomain().getCodeSource().getLocation().toString()); - result.put("sdkOrigin", p.studio.compiler.pbs.stdlib.StdlibEnvironmentResolver.class.getProtectionDomain().getCodeSource().getLocation().toString()); - result.put("javaVersion", System.getProperty("java.version")); - result.put("pipelineOrigin", BuilderPipelineService.class.getProtectionDomain().getCodeSource().getLocation().toString()); - var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())); - var logs = LogAggregator.with(LOG::add); - var phases = new ArrayList>(); - result.put("phases", phases); - result.put("status", "infrastructure_failure"); - try { - if (publicEntry) { - var compiled = BuilderPipelineService.INSTANCE.compile(ctx, logs); - result.put("diagnostics", compiled.diagnostics().stream().map(i -> issue(i, ctx)).toList()); - result.put("status", "compiled"); - } else { - var analyzed = BuilderPipelineService.INSTANCE.analyze(ctx, logs); - var phase = new LinkedHashMap(); - phase.put("phase", "analysis"); - phase.put("diagnostics", analyzed.diagnostics().stream().map(i -> issue(i, ctx)).toList()); - boolean failed = analyzed.diagnostics().stream().anyMatch(BuildingIssue::isError); - phase.put("status", failed ? "failed" : "passed"); - phases.add(phase); - if (failed) result.put("status", "analysis_failed"); - else { - var stages = new ArrayList(); - stages.add(new LowerToIRVMPipelineStage()); - if (optimize) stages.add(new OptimizeIRVMPipelineStage()); - stages.add(new EmitBytecodePipelineStage()); - stages.add(new LinkBytecodePipelineStage()); - stages.add(new VerifyBytecodePipelineStage()); - result.put("status", "compiled"); - for (var stage : stages) { - if (!optimize && stage instanceof EmitBytecodePipelineStage) ctx.optimizedIrvm = ctx.irvm; - var issues = stage.run(ctx, logs).asCollection(); - var item = new LinkedHashMap(); - item.put("phase", stage.getClass().getSimpleName()); - item.put("diagnostics", issues.stream().map(i -> issue(i, ctx)).toList()); - boolean errors = issues.stream().anyMatch(BuildingIssue::isError); - item.put("status", errors ? "failed" : "passed"); - phases.add(item); - if (errors) { result.put("status", "compile_failed"); break; } - } - } - } - if (result.get("status").equals("compiled")) { - Path cartridge = root.resolve("cartridge"); - Files.createDirectories(cartridge); - Files.write(cartridge.resolve("program.pbx"), ctx.bytecodeBytes); - var manifest = new LinkedHashMap(); - manifest.put("magic", "PMTU"); manifest.put("cartridge_version", 1); - manifest.put("app_id", 113); manifest.put("title", "PBS production assertion fixture"); - manifest.put("app_version", "1.0.0"); manifest.put("app_mode", "Game"); - manifest.put("capabilities", List.of()); manifest.put("asset_table", List.of()); manifest.put("preload", List.of()); - MAPPER.writerWithDefaultPrettyPrinter().writeValue(cartridge.resolve("manifest.json").toFile(), manifest); - result.put("cartridge", cartridge.toString()); - result.put("bytecodeBytes", ctx.bytecodeBytes.length); - result.put("bytecodeSha256", HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(ctx.bytecodeBytes))); - } - } catch (Throwable failure) { - result.put("status", failure instanceof p.studio.compiler.exceptions.BuildException - ? "public_compile_rejected" : "pipeline_exception"); - result.put("exception", causes(failure)); - if (failure instanceof p.studio.compiler.exceptions.BuildException buildFailure) - result.put("diagnostics", buildFailure.getDiagnostics().stream().map(i -> issue(i,ctx)).toList()); - } - if (ctx.fileTable != null) { - var files = new LinkedHashMap(); - for (int i = 0; i < ctx.fileTable.size(); i++) { - var f = ctx.fileTable.get(new FileId(i)); - files.put(Integer.toString(i), f.getCanonPath().toString()); - } - result.put("files", files); - } - if (ctx.irBackend != null) { - var functions = new ArrayList>(); - for (var fn : ctx.irBackend.getExecutableFunctions()) { - var file = ctx.fileTable.get(fn.fileId()).getCanonPath(); - if (!file.startsWith(root)) continue; - var f = new LinkedHashMap(); - f.put("callableId", fn.callableId().toString()); f.put("name", fn.callableName()); - f.put("file", root.relativize(file).toString()); - f.put("instructions", fn.instructions().stream().map(Object::toString).toList()); - functions.add(f); - } - result.put("projectFunctions", functions); - } - result.put("inputs", p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.inputs( - p.studio.compiler.source.diagnostics.SourceReference.snapshot(ctx.fileTable), root)); - result.put("logs", LOG); - Path report = Path.of(args[2]); Files.createDirectories(report.getParent()); - MAPPER.writerWithDefaultPrettyPrinter().writeValue(report.toFile(), result); - System.out.println(result.get("status") + " " + root.getFileName()); - } - - static Map issue(BuildingIssue i, BuilderPipelineContext ctx) { - var sources = p.studio.compiler.source.diagnostics.SourceReference.snapshot(ctx.fileTable); - return p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.issue(i, sources, - p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.capturedText(ctx.fileTable), - ctx.rootProjectPathCanon, ANALYSIS_ID + ":" + issueIndex++); - } - - static List> causes(Throwable t) { - var result = new ArrayList>(); - for (int n = 0; t != null && n < 8; n++, t = t.getCause()) - result.add(Map.of("class", t.getClass().getName(), "message", String.valueOf(t.getMessage()))); - return result; - } -} diff --git a/tools/pbs-production-corpus/README.md b/tools/pbs-production-corpus/README.md deleted file mode 100644 index 689029e4..00000000 --- a/tools/pbs-production-corpus/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# PBS production corpus qualification - -Owner: compiler/pbs. This maintained runner preserves the frozen 28-case input and writes each run to a new directory. It never rebuilds or writes the runtime provider and does not modify a game workspace or memcard. - -Build the candidate with the required regression gate, then run the corpus: - -```bash -./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-compiler:prometeu-build-pipeline:test :prometeu-lsp:prometeu-lsp-v1:test :prometeu-app:test :prometeu-app:installedKnowledgeTest --console=plain -``` - -```bash -python3 tools/pbs-production-corpus/run.py --corpus prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/resources/production-regressions/cases.json --distribution prometeu-app/build/install/prometeu-app --runtime-headless /absolute/existing/prometeu-headless --output build/pbs-production-corpus/new-run -``` - -Each case is compiled in a fresh JVM/project outside the checkout. Checkout mode puts current classes/resources first; installed mode includes only candidate JARs and runs outside the checkout. The runner verifies candidate product class freshness and records Java, SDK/compiler origins, JAR/source/PBX/manifest/runtime hashes, Git/worktree state, diagnostic phases and protocol transcripts. - -The required corpus produces 168 observations: 28 cases × checkout/installed × optimized production stages, investigation-only unoptimized stages, and the public optimized facade. Unoptimized means omitting OptimizeIRVMPipelineStage and emitting original IRVM; it is not a public compiler flag. The expected runtime matrix is 108 executions: 27 compiled cases × checkout/installed × two optimization configurations, with 104 normal three-frame successes and four deliberately faulting controls. The file-private case must remain a structured source rejection in all six compile configurations. - -Use --select id1,id2 or --origins checkout/installed for focused investigation. Without those restrictions, exit zero requires the complete expected matrix and classifications. Output directories cannot be reused or target published lessons and their evidence. Runtime processes are terminated and waited for on every path. Logs are local evidence, while summary.json and per-case JSON preserve structured results. - -The focused-cases.json resource is an additional matrix for contextual overloads, noncommutative receiver/argument order, original global storage, service singleton identity and privacy. It does not replace or alter the frozen corpus. Successful compiler proof does not imply qualification of an installed runtime distribution or a live Studio session. The Studio tests independently preserve MCP/LSP diagnostic contracts. - -The completed production corrections, original baseline and separate post-fix reports are consolidated in [LSN-0106](../../discussion/lessons/DSC-0111-pbs-production-reproductions-and-fixes/LSN-0106-pbs-production-binding-and-lowering-corrections.md). - -## Installed authoring contracts - -The existing installed reference corpus includes `production/GUIDE.md` and 21 -complete positive/negative projects covering eight authoring scenarios. Run -`:prometeu-app:installedKnowledgeTest` first; it compiles their actual installed -resources outside the checkout and emits artifacts and source/JAR/catalog hashes -under `prometeu-compiler/prometeu-build-pipeline/build/registry-conformance/production-contracts`. -Then qualify their behavioral assertions and exact bounds faults using the same -headless protocol harness as the original corpus: - -```bash -python3 tools/pbs-production-corpus/qualify-installed-contracts.py --artifacts prometeu-compiler/prometeu-build-pipeline/build/registry-conformance/production-contracts --distribution prometeu-app/build/install/prometeu-app --runtime-headless /absolute/existing/prometeu-headless --output build/pbs-installed-contracts/new-run -``` - -The qualifier rejects a distribution whose JAR hashes differ from the compilation -record. It preserves separate discovery/compilation/rejection/execution results, -checks fault code 3 rather than accepting any trap, and verifies worker termination. -Gfx is qualified for installed API compilation; graphical execution and pixel -output are not claimed. Existing runtime binaries are executed without writing -their repository. The original frozen corpus and its matrix remain unchanged. diff --git a/tools/pbs-production-corpus/qualify-installed-contracts.py b/tools/pbs-production-corpus/qualify-installed-contracts.py deleted file mode 100644 index a4285cec..00000000 --- a/tools/pbs-production-corpus/qualify-installed-contracts.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python3 -"""Qualify artifacts compiled from installed PBS references using the existing runtime harness.""" -import argparse -import importlib.util -import json -from pathlib import Path -import shutil -import sys -import tempfile - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--artifacts', type=Path, required=True) - parser.add_argument('--distribution', type=Path, required=True) - parser.add_argument('--runtime-headless', type=Path, required=True) - parser.add_argument('--output', type=Path, required=True) - args = parser.parse_args() - sys.dont_write_bytecode = True - spec = importlib.util.spec_from_file_location('pbs_corpus', Path(__file__).with_name('run.py')) - harness = importlib.util.module_from_spec(spec) - spec.loader.exec_module(harness) - artifacts = args.artifacts.resolve(strict=True) - distribution = args.distribution.resolve(strict=True) - binary = args.runtime_headless.resolve(strict=True) - output = args.output.resolve() - if output.exists(): - parser.error('Output must be a new directory; evidence is never overwritten') - output.mkdir(parents=True) - compilation = json.loads((artifacts / 'compilation.json').read_text()) - assert compilation['passed'] - jars = {p.name: harness.sha(p) for p in (distribution / 'lib').glob('*.jar')} - assert jars == compilation['provenance']['installedJarSha256'], 'Compiled artifacts must match this distribution' - scratch = Path(tempfile.mkdtemp(prefix='pbs-installed-contracts-')) - observations = [] - for case in compilation['cases']: - expected = case['expectation']['expectedRuntime'] - if expected == 'not-run': - continue - assert case['compileStatus'] == 'compiled' and case['matchesExpectation'] and case['sourceUnchanged'] - cartridge = artifacts / case['id'] - assert harness.sha(cartridge / 'program.pbx') == case['bytecodeSha256'] - assert harness.sha(cartridge / 'manifest.json') == case['manifestSha256'] - saved = output / 'artifacts' / case['id'] - shutil.copytree(cartridge, saved) - result = harness.execute(binary, str(saved), scratch / case['id']) - fault = result.get('fault') - if isinstance(fault, dict) and 'fault' in fault: - fault = fault['fault'] - code = (fault or {}).get('trap', {}).get('code') - matched = result['observedRuntime'] == expected and result['workerTerminated'] - if expected == 'fault': - matched &= code == case['expectation']['faultCode'] - result.update(id=case['id'], expectedRuntime=expected, expectedFaultCode=case['expectation'].get('faultCode'), - observedFaultCode=code, matchesExpectation=matched) - harness.write(output / 'execution' / (case['id'] + '.json'), result) - observations.append({k: result[k] for k in ['id', 'expectedRuntime', 'observedRuntime', 'observedFaultCode', 'matchesExpectation', 'workerTerminated']}) - print(case['id'], result['observedRuntime'], code, matched, flush=True) - shutil.copy2(artifacts / 'compilation.json', output / 'compilation.json') - provenance = {'installed': compilation['provenance'], 'distribution': str(distribution), - 'runtime': str(binary), 'runtimeSha256': harness.sha(binary), 'runnerSha256': harness.sha(__file__), - 'harnessSha256': harness.sha(Path(__file__).with_name('run.py')), 'scratch': str(scratch), - 'runtimeWrites': False, 'gfxExecution': 'not-run; installed API compilation only'} - harness.write(output / 'provenance.json', provenance) - summary = {'compileClassifications': len(compilation['cases']), 'executions': observations, - 'passed': bool(observations) and all(x['matchesExpectation'] for x in observations)} - harness.write(output / 'summary.json', summary) - harness.write(output / 'checksums.json', {str(p.relative_to(output)): harness.sha(p) for p in output.rglob('*') if p.is_file()}) - print(json.dumps({'compileClassifications': summary['compileClassifications'], 'executionCount': len(observations), 'passed': summary['passed']})) - return 0 if summary['passed'] else 1 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/tools/pbs-production-corpus/run.py b/tools/pbs-production-corpus/run.py deleted file mode 100644 index c20a3a96..00000000 --- a/tools/pbs-production-corpus/run.py +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/env python3 -"""Isolated production PBS regression matrix. Never writes the received baseline or runtime checkout.""" -import argparse -import hashlib -import json -import os -from pathlib import Path -import platform -import selectors -import signal -import subprocess -import tempfile -import time -import zipfile - -ROOT = Path(__file__).resolve().parents[2] -MODULES = ["prometeu-infra", "prometeu-animation", "prometeu-compiler/prometeu-compiler-core", - "prometeu-compiler/prometeu-frontend-api", "prometeu-compiler/frontends/prometeu-frontend-pbs", - "prometeu-compiler/prometeu-frontend-registry", "prometeu-compiler/prometeu-deps", - "prometeu-compiler/prometeu-build-pipeline"] - - -def sha(path): - return hashlib.sha256(Path(path).read_bytes()).hexdigest() - - -def write(path, data): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n") - - -class Session: - def __init__(self, binary, directory): - self.stderr_path = directory / "runtime.stderr" - self.stderr = self.stderr_path.open("wb") - self.process = subprocess.Popen([str(binary), "--stdio"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=self.stderr, cwd=directory, start_new_session=True) - self.selector = selectors.DefaultSelector() - self.selector.register(self.process.stdout, selectors.EVENT_READ) - self.buffer = bytearray() - self.transcript = [] - self.request = 0 - - def event(self): - deadline = time.monotonic() + 12 - while b"\n" not in self.buffer: - remaining = deadline - time.monotonic() - if remaining <= 0 or not self.selector.select(remaining): - raise TimeoutError("Runtime reply deadline") - data = os.read(self.process.stdout.fileno(), 65536) - if not data: - raise EOFError("Runtime closed stdout") - self.buffer.extend(data) - line, _, self.buffer = self.buffer.partition(b"\n") - value = json.loads(line) - self.transcript.append({"direction": "received", "message": value}) - return value - - def call(self, command, params=None): - self.request += 1 - request = {"requestId": f"pbs-corpus-{self.request}", "command": command, "params": params or {}} - self.transcript.append({"direction": "sent", "message": request}) - self.process.stdin.write(json.dumps(request).encode() + b"\n") - self.process.stdin.flush() - while True: - response = self.event() - if response.get("requestId") != request["requestId"]: - raise AssertionError("Unexpected response correlation") - if response.get("type") == "progress": - continue - if "error" in response: - raise RuntimeError(json.dumps(response["error"])) - return response.get("result") - - def close(self): - try: - if self.process.poll() is None: - try: - self.call("shutdown") - self.process.wait(timeout=5) - except Exception: - os.killpg(self.process.pid, signal.SIGKILL) - self.process.wait(timeout=5) - finally: - self.selector.close() - self.stderr.close() - self.process.stdin.close() - self.process.stdout.close() - - -def execute(binary, cartridge, work): - work.mkdir(parents=True) - result = {"observedRuntime": "infrastructure_failure"} - session = Session(binary, work) - try: - hello = session.event() - assert hello["type"] == "hello" and hello["protocolVersion"]["major"] == 1 - required = ["boot", "advance", "get_state", "get_fault", "shutdown"] - assert set(required) <= set(hello["capabilities"]) - result["hello"] = hello - session.call("initialize", {"protocolVersion": {"major": 1, "minor": min(1, hello["protocolVersion"]["minor"])}, - "requiredCapabilities": required}) - result["boot"] = session.call("boot", {"path": cartridge}) - result["advance"] = advance = session.call("advance", {"frames": 3}) - result["fault"] = fault = session.call("get_fault") - result["state"] = session.call("get_state") - fault = fault.get("fault") if isinstance(fault, dict) and "fault" in fault else fault - result["observedRuntime"] = "fault" if fault is not None else "passed" if advance.get("completed") == 3 else "incomplete" - except Exception as failure: - result["exception"] = {"class": type(failure).__name__, "message": str(failure)} - finally: - session.close() - result.update(workerTerminated=session.process.poll() is not None, processExitCode=session.process.returncode, - transcript=session.transcript, stderr=session.stderr_path.read_text(errors="replace")) - return result - - -def source_rejection(report): - issues = report.get("diagnostics", []) + [i for p in report.get("phases", []) for i in p.get("diagnostics", [])] - return report.get("status") in ("analysis_failed", "public_compile_rejected") and any(i.get("severity") == "ERROR" and (i.get("failureKind") == "program-rejection" or str(i.get("code", "")).startswith("E_")) for i in issues) \ - and not any(i.get("failureKind") in ("internal-failure", "infrastructure-failure", "verification-limit") for i in issues) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--corpus", type=Path, required=True) - parser.add_argument("--distribution", type=Path, required=True) - parser.add_argument("--runtime-headless", type=Path, required=True) - parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--select", help="Comma-separated IDs; omitted for the complete 168/108 gate") - parser.add_argument("--origins", choices=["checkout", "installed", "both"], default="both") - args = parser.parse_args() - corpus, distribution, binary, output = args.corpus.resolve(strict=True), args.distribution.resolve(strict=True), args.runtime_headless.resolve(strict=True), args.output.resolve() - if output.exists(): - parser.error("Output must be a new directory; evidence is never overwritten") - lessons = ROOT / "discussion/lessons" - if output == lessons or lessons in output.parents: - parser.error("Published lessons and their evidence are read-only") - output.mkdir(parents=True) - cases = json.loads(corpus.read_text())["cases"] - if args.select: - selected = set(args.select.split(",")); assert selected <= {c["id"] for c in cases} - cases = [c for c in cases if c["id"] in selected] - scratch = Path(tempfile.mkdtemp(prefix="pbs-production-corpus-")) - assert not scratch.is_relative_to(ROOT) - java, javac = distribution / "runtime/bin/java", distribution / "runtime/bin/javac" - jars = sorted((distribution / "lib").glob("*.jar")); assert jars - # Verify candidate product classes before mixing checkout classes with third-party dependencies. - freshness = [] - for module in MODULES: - jar = next(p for p in jars if p.name == Path(module).name + ".jar" or p.name.startswith(Path(module).name + "-")) - with zipfile.ZipFile(jar) as archive: - classes = ROOT / module / "build/classes/java/main" - compared = list(classes.rglob("*.class")); assert compared - different = [str(p.relative_to(classes)) for p in compared if archive.read(str(p.relative_to(classes))) != p.read_bytes()] - assert not different, (module, different) - freshness.append({"module": module, "jarSha256": sha(jar), "matchingClasses": len(compared)}) - provenance = {"schemaVersion": 1, "corpusSha256": sha(corpus), "runtime": str(binary), "runtimeSha256": sha(binary), - "platform": platform.platform(), "gitHead": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), - "worktreeStatus": subprocess.check_output(["git", "status", "--short"], cwd=ROOT, text=True).splitlines(), - "java": subprocess.run([str(java), "-version"], capture_output=True, text=True, check=True).stderr, - "distribution": str(distribution), "jars": {p.name: sha(p) for p in jars}, "candidateFreshness": freshness, - "probeSha256": sha(Path(__file__).resolve().with_name("PbsProductionCorpusProbe.java")), "runnerSha256": sha(__file__), - "scratch": str(scratch), "unoptimizedVariant": "Investigation-only: omit OptimizeIRVMPipelineStage and emit original IRVM; not a public compiler flag"} - write(output / "provenance.json", provenance) - observations, executions = [], [] - origins = ["checkout", "installed"] if args.origins == "both" else [args.origins] - for origin in origins: - installed = os.pathsep.join(map(str, jars)) - entries = [ROOT / m / suffix for m in MODULES for suffix in ["build/classes/java/main", "build/resources/main"] if (ROOT / m / suffix).exists()] - cp = os.pathsep.join(map(str, entries)) + os.pathsep + installed if origin == "checkout" else installed - classes = scratch / origin / "classes"; classes.mkdir(parents=True) - subprocess.run([str(javac), "-proc:none", "-cp", cp, "-d", str(classes), str(Path(__file__).resolve().with_name("PbsProductionCorpusProbe.java"))], cwd=scratch, check=True) - for case in cases: - for variant in ["optimized", "unoptimized", "optimized-public"]: - project = scratch / origin / case["id"] / variant - for name, source in case["files"].items(): - path = project / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text(source) - report_path = output / "compilation" / origin / f"{case['id']}-{variant}.json" - cmd = [str(java), "-cp", str(classes) + os.pathsep + cp, "PbsProductionCorpusProbe", str(project), "unoptimized" if variant == "unoptimized" else "optimized", str(report_path)] - if variant == "optimized-public": cmd.append("public") - try: - completed = subprocess.run(cmd, cwd=scratch, capture_output=True, text=True, timeout=50, check=True) - report = json.loads(report_path.read_text()); report["stderr"] = completed.stderr - except Exception as failure: - report = {"status": "infrastructure_failure", "exception": {"class": type(failure).__name__, "message": str(failure)}} - expected = case["expectedCompile"] - matched = report["status"] == "compiled" if expected == "compiled" else source_rejection(report) - if origin == "installed" and report.get("frontendOrigin"): - assert all(str(distribution) in report.get(key, "") for key in ["frontendOrigin", "pipelineOrigin", "sdkOrigin"]) - sources_unchanged = all((project / name).read_text() == source for name, source in case["files"].items()) - assert sources_unchanged - identity = {"caseId": case["id"], "origin": origin, "variant": variant, "sourceSha256": case["sourceSha256"]} - report.update(identity, expectedCompile=expected, matchesExpectation=matched, sourcesUnchanged=sources_unchanged) - if report["status"] == "compiled": - cartridge = Path(report["cartridge"]) - for name in ["manifest.json", "program.pbx"]: - target = output / "artifacts" / origin / case["id"] / variant / name - target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes((cartridge / name).read_bytes()) - report["manifestSha256"] = sha(cartridge / "manifest.json") - write(report_path, report); observations.append({**identity, "status": report["status"], "matchesExpectation": matched, "report": str(report_path.relative_to(output))}) - print(origin, case["id"], variant, report["status"], matched, flush=True) - if report["status"] == "compiled" and variant != "optimized-public": - result = execute(binary, report["cartridge"], project / "execution") - result.update(identity, bytecodeSha256=report["bytecodeSha256"], expectedRuntime=case["expectedRuntime"]) - result["matchesExpectation"] = result["observedRuntime"] == case["expectedRuntime"] and result["workerTerminated"] - path = output / "execution" / origin / f"{case['id']}-{variant}.json"; write(path, result) - executions.append({**identity, "observedRuntime": result["observedRuntime"], "matchesExpectation": result["matchesExpectation"], "report": str(path.relative_to(output))}) - write(output / "summary.json", {"compilation": observations, "execution": executions}) - failures = [x for x in observations + executions if not x["matchesExpectation"]] - expected_runs = sum(c["expectedCompile"] == "compiled" for c in cases) * len(origins) * 2 - complete = len(observations) == len(cases)*len(origins)*3 and len(executions) == expected_runs - summary = {"compilation": observations, "execution": executions, "compileCount": len(observations), "executionCount": len(executions), - "normalSuccesses": sum(x["observedRuntime"] == "passed" for x in executions), "deliberateFaults": sum(x["observedRuntime"] == "fault" and x["caseId"] == "runtime-trap-control" for x in executions), - "complete": complete, "failures": failures, "passed": complete and not failures} - write(output / "summary.json", summary) - write(output / "checksums.json", {str(p.relative_to(output)): sha(p) for p in output.rglob("*") if p.is_file()}) - print(json.dumps({k:v for k,v in summary.items() if k not in ("compilation", "execution", "failures")})) - return 0 if summary["passed"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/pbx-conformance/README.md b/tools/pbx-conformance/README.md deleted file mode 100644 index 6aad86aa..00000000 --- a/tools/pbx-conformance/README.md +++ /dev/null @@ -1,545 +0,0 @@ -# Studio PBX producer conformance - -Owner: compiler/general. This harness uses the production runtime loader and VM; -it does not implement a Java approximation of runtime admission. - -## PBS memcard and MemcardBuffer qualification - -Generate the production PBS corpus and the actual installed-JAR example, then run -both runtime profiles without modifying the runtime checkout: - -```sh -./gradlew test :prometeu-app:installedKnowledgeTest --console=plain -CARGO_TARGET_DIR=/tmp/studio-pbx-memcard-target python3 tools/pbx-conformance/run.py --runtime ../runtime --memcard-only -CARGO_TARGET_DIR=/tmp/studio-pbx-memcard-target python3 tools/pbx-conformance/run.py --runtime ../runtime --memcard-only --release -``` - -The dedicated carrier has concrete Array storage, capacity 0..4096, zero -initialization, checked byte access and reference aliasing. Ordinary PBS arrays -keep vacancy/optional semantics. The corpus checks all 14 native imports, both -producer optimizer variants, typed source boundaries and origin protection; -source aliases and canonical imported/reexported hooks; named evaluation order; -exact four-byte save/remount and no resave; 4096-byte transfers; 64-slot admission; -clear/commit; retained requests and BUSY; memory-only/pause/resume; public title, -format-version and 32x32 icon publication; absent/read-only/corrupt media; controlled -FAILURE/INDETERMINATE; hook refusal/trap/fuel; capacity/index/value/transfer traps. -The status-first facade forwards native calls without an intermediate typed RET, -so failed-domain Null payloads reach the caller's status check unchanged. - -`memcard.rs` executes the production Firmware/SystemOS, VM, FileMemcard and its -shared worker. Fault storage distinguishes pre-publication failure from uncertain -metadata publication. The installed-JAR source fixture is also executed natively. -This is **native production-host evidence**. Multiple Firmware instances and a -file remount in this process do not establish save/reopen through the configured -installed runtime CLI/JSONL protocol. The separate process gate below consumes -the now-published provider surface for storage and explicit choices. -No alternative process protocol or physical power-cut qualification is claimed. - -The separate Studio process gate now consumes the published protocol 1.1 memcard -extension through HeadlessProcessGateway and the configured installation: - -```sh -./gradlew :prometeu-app:memcardProcessTest -PstudioRuntimeInstall=/absolute/extracted/installation -``` - -It builds actual PBS through the compiler and Studio shipper, requires a native -terminal commit SUCCESS, terminates the writer, then starts separate readers for -versions 1 and 2 with identical uint32 app_id. Both optimizer variants are required. -The reader's reachable entry/role graph contains no saving or presentation calls; -it validates exactly 00 7f 80 ff before rendering its observed oracle. Each read -leaves the complete image byte-identical and no native request submitted. A second -case proves missing-file open does not create, memory-only is explicit and dirty -shutdown refusal preserves the channel until explicit discard. Runtime dev/release -binary layouts and an extracted distribution are identified separately in evidence. - -## PBS Map and Keyval qualification - -Generate the mandatory Map corpus and actual installed-JAR example, then execute -the dedicated verifier in both runtime profiles: - -```sh -./gradlew :prometeu-architecture-tests:test --tests '*PbsMapKeyvalTest' :prometeu-app:installedKnowledgeTest --console=plain -CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime --map-only -CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime --map-only --release -``` - -Each non-GC source case has ordinary/optimized PBS producer variants, independent -of the Rust dev/release profile. The manifest names every required success/fault, -resource, injection, GC, import and installed fixture; missing files fail. The -full harness includes Map separately from its historical catch-all PBS verifier. - -The corpus covers typed non-positional keys; default/explicit Identity; optional -V and previous-value presence; original-key retention under content policies; -read-only Keyval instance identity; collisions/negative full hashes; rehash and -capture callback counters; complete tuple/native/contract groups; evaluation order; -alias reentrancy and permitted callback reads; and the shared snapshot state table. - -Resource fixtures compare attempted instruction prefixes with successful -instruction prefixes under lowered production quotas. They separate installed -guard writes from structural mutation and measure old/candidate table/node and -snapshot/keyval peaks. A named test-only allocation after the real candidate-table -store qualifies permitted post-write incomplete invariants; production SDK has no -injected probe. Natural quota refusal counts are reported separately. - -Real safepoints check independent key/value roots, obsolete-value release after -replacement, removed-key/value reclamation, Map-node reclamation, captured Keyvals, -consumed Cursor prefixes, retained final current and release after all owners exit. -Imported/reexported and installed examples execute through the production loader -and VM and actually construct the shared entry Cursor. This is local semantic and -resource qualification, not a performance benchmark or a new provider contract. - -From the Studio root: - -```sh -./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' --tests '*RuntimeCatalogPipelineTest' -./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest' --tests '*PbsClosuresTest' --tests '*PbsGenericContractsTest' -python3 tools/pbx-conformance/run.py --runtime ../runtime -``` - -The Java tests generate PBX in the build-pipeline module's -`build/registry-conformance`. `run.py` creates a temporary Cargo project, copies -the runtime lockfile and references its bytecode/hal/vm/system crates by path. -It never modifies the runtime checkout. Add `--online` for an uncached machine; -by default Cargo uses only cached dependencies. Java 21, Rust and the runtime -checkout's dependencies are required. - -The output identifies runtime revision, OS/architecture and load configuration. -Positive fixtures distinguish loading from execution. The vec2 signature fixture -is deliberately load-only because its entry requires arguments. Native binding -uses SYSTEM for the positive case and NONE for missing-capability rejection; -all other cases use NONE. Resource tests explicitly lower default limits. - -## PBS controlled guest lifecycle qualification - -Generate the source corpus and installed example, then run both runtime profiles: - -```sh -./gradlew :prometeu-architecture-tests:test --tests '*PbsGuestLifecycleTest' :prometeu-app:installedKnowledgeTest -python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only -python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only --release -``` - -`PbsGuestLifecycleTest` emits ordinary/optimized production PBX for both hooks, -each independently and neither, ordinary direct calls, fatal traps, total fuel -exhaustion and successful calls spanning slices. Arbitrary function names and -unmarked functions named BeforePause/BeforeResume distinguish role metadata from -name conventions. An actual workspace import/reexport case selects one original -declaration without requiring colocation with Frame. A conflicting declaration -must fail project analysis. Synthetic binary fixtures explicitly cover direct -and transitive FRAME_SYNC rejection; they do not add PBS sync syntax. - -`lifecycle.rs` loads these images with the production VM and runs the production -Firmware/SystemOS foreground path using the standard TestPlatform hardware. -Home/resume asserts exact ordered guest effects, unchanged continuation PC and -game-session ticks/frames during hooks, preserved heap/global state and a single -Init execution. Direct suspension and Shell foreground handoff must not add a -reaction tick. A partial frame retains its existing operand and call frame while -controlled hooks run. Ordinary direct calls do not acquire a controlled context. - -The independent 1,500,000-cycle fuel budget survives slices and debugger stops; -single stepping uses the same accounting. Fatal trap/fuel/sync cases cannot run -subsequent gameplay or publish a logical frame. After a crash, counters are read -from the retained game session rather than the newly active crash UI. Probe -functions run only as terminal observations after continuation/frame assertions. - -The runner adds production firmware/driver dependencies to its temporary Cargo -project. Sources, manifests, lockfiles and build outputs in the runtime checkout -remain untouched. This is local lifecycle conformance; installed runtime/game -qualification and MemcardBoot/persistence remain separate scopes. - -Negative fixtures mutate Java-produced bytes independently of the writer to -exercise malformed input that the writer correctly refuses to construct. -Initialization JSON comes from `prometeu_system::CrashReport`, and is checked -against the runtime's published headless schema. Saved JSON files remain under -the generated fixture directory. Studio process tests replay selected observed -payloads from `prometeu-app/src/test/resources/runtime` and assert unchanged MCP -projection, including null executed PC and nested verifier context. - -## Known upstream schema defect - -At runtime `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, the LoadReason Rust enum -includes LifecycleRole, LifecycleSignature, DuplicateLifecycleRole and -NonFiniteValue, absent from the published JSON schema enum. This corpus -observes LifecycleRole and NonFiniteValue. The harness prints an explicit -`UPSTREAM SCHEMA GAP` for those two reasons and verifies that adding exactly -the missing enum value makes the original payload valid. It never alters the -payload or reports those cases as conforming to the unmodified schema. Any -other schema failure remains fatal. Track the runtime correction in AGD75; -remove the exception once the schema is corrected. - -The original registry/catalog fixtures qualify common backend production. The -PBS fixtures below additionally qualify source lowering; this harness does not -claim installed-runtime deployment or memcard persistence. - -## Runtime catalog consumer fixtures - -The catalog corpus adds common-IR Random calls with an aliased handle, a discarded -first result, mixed next/nextf/range calls and a subsequent next. The VM checks the -independent seed-42 handoff vector and identical charged work before/after -optimization. Constants are compared slot-by-slot against runtime materialization, -including exact Float bits and both slots of `vec2.zero`. Pool deduplication may -share a value but cannot omit a group component. - -A known zero-argument touch query loads and traps `TRAP_UNAVAILABLE` without a -hardware context. A removed endpoint ID is rejected even after an unreachable -HALT. `color.html_rgba` executes with a String value and rejects a proven null -at load time, matching the runtime verifier's stricter rule despite the -dispatcher's nullable String carrier. These are distinct outcomes. Run the separate provider-export check with -`python3 tools/runtime-catalog/verify.py --runtime ../runtime` to compare the -selected source revision, imported CSV bytes and exporter output as well. - - -## PBS source and input qualification - -`PbsRuntimeAlignmentTest` compiles actual SDK declarations and source programs -through the PBS frontend, production common IR, typed Registry and PBX writer. -Its 114 fixtures execute on the selected runtime: all 48 Pad combinations with -both literal Button arguments and enum locals passed through a typed function, -six Touch queries, numeric boundaries/conversions/faults, builtin groups, -String, fixed multiple returns and named application with observable Y,X effects. - -The controlled input platform asserts the exact button/coordinate reader and -one read per public query. Each query is also executed without a platform to -prove TRAP_UNAVAILABLE. The loaded PBS registries are checked for the defaults -of all eight existing value types, including null String, positive Float zero -and complete vec2/pixel groups. No source constructors or new collection API -are introduced to test storage defaults. - -The harness requires the complete fixture count. It must not pass by skipping -missing PBS fixtures. Integer arithmetic wrapping is distinct from checked -Int64-to-Int32 narrowing and Float numeric-range faults. The full installed -knowledge gate remains separate and mandatory for SDK resource/producer -integration. - -## PBS typed arrays, optional and Struct/contract execution - -`PbsStructuredValuesTest` generates 27 mandatory `pbs-structured-*` fixtures. -They cover contextual arrays, nested levels, vacancy/zero, clear/length, aliasing, -int/long bounds, single evaluation, lazy optional fallback, inferred/explicit -optional tuples, native vec2 groups, fields and constructors, overloads and Self, -contract elements/dispatch, imported services/structs/contracts, global file-init, -and the installed example. The runtime harness names every required fixture; -a missing file is an error. - -Eighteen additional runs lower GuestBytes or HandleSlots to 0, 1 or 2. They assert -resource faults, bounded accounting, no object publication at zero quota, and -release of session ownership. The integer-storage fixture succeeds with one -handle total, proving that its three integers do not allocate individual boxes. -String session accounting is checked after each structured execution. - -The GC fixture compiles all allocations, roots and post-collection reads from PBS. -A test-only driver hook replaces one isolated marker assignment with FRAME_SYNC -and NOPs without changing code offsets; it does not add PBS sync syntax. At the -real runtime safepoint, at least 1,100 discarded objects are reclaimed while -nested references, tuples and strings remain readable. `resource-diagnostics` -is enabled solely for observation. Default production ceilings and GC threshold -are unchanged outside the explicitly lowered quota runs. This is semantic and -resource conformance, not a performance benchmark or installed game qualification. - -## PBS first-class functions and closure lifetime - -`PbsClosuresTest` adds nine mandatory source/load/execute fixtures: named and -anonymous functions, snapshots, shared objects/arrays, nested function captures, -complete tuple groups and contract receivers, independent environments, Fn fields -and overload selection, imported functions, and the installed example. Each -returns 42. Six additional GuestBytes/HandleSlots runs at limits 0, 1 and 2 check -closure allocation faults and session ownership, bringing structured quota runs -to 24. - -The tenth fixture, `closure-frame-lifecycle.pbx`, uses the existing production -lifecycle assembler without bytecode patching. Its first frame stores a closure -capturing an object; the next frame invokes it twice (41, then 42) and drops the -reference. Each of three frames also discards 1,200 closures. The harness asserts -threshold collections, retained closure/object reachability after frame one, -and reclamation after release. The remaining root is the global array. -PBS publishes FRAME_ROOT and the existing guarded wrapper returns normally. -No sync syntax, new frame integration, suspension or coroutine is introduced. - -## PBS service constants and runtime math - -`PbsRuntimeMathTest` produces 261 independent numeric cases in both ordinary and -optimized bytecode (522 mandatory executions per runtime profile), covering all -26 math/mathf signatures. The checked-in corpus preserves 240 provider scalar -fixture rows and exact contract examples (duplicates removed); provenance is in -`prometeu-architecture-tests/src/test/resources/math/provenance.txt`. - -The harness verifies exact bits/faults, selected intrinsic identity and one -retained call per case. Single-step charging is compared with the provider's -opcode costs and independent fixture call cost; full-budget charging must equal -their sum, and optimization must preserve total cycles. Additional cases exercise -pi/tau, literal sin, ordinary int/long service constants, constant dependencies, -and real module imports with service aliases. The installed example also imports -both SDK services, so installedKnowledgeTest covers their packaged resources. - -```sh -./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeMathTest' -python3 tools/pbx-conformance/run.py --runtime ../runtime --math-only -python3 tools/pbx-conformance/run.py --runtime ../runtime --math-only --release -``` - -Omit `--math-only` for the full existing corpus. `--release` selects the optimized -Rust runtime harness; it is independent of the PBS optimizer variants included in -every run. Optional `CARGO_TARGET_DIR` can retain build artifacts outside the -runtime checkout. Each invocation prints runtime revision, platform, profile, -features, lockfile and provider catalog/oracle hashes. Local evidence qualifies -macOS/arm64 only; macOS/x86_64 and Linux/x86_64 remain pending. - -## PBS explicit Random integration - -`PbsRuntimeRandomTest` adds 226 source fixtures plus one real SDK import/alias -fixture. The 48 unchanged provider oracle rows produce 192 exact integer/Float -cases (six seeds, eight draws, two output kinds and two optimizer variants). -The remaining paired fixtures cover mixed/discarded draws, independent objects, -locals/globals/fields/arrays/parameters/results/captures, named/positional effects, -unit/extreme ranges, invalid limits, null and typed-null Dynamic storage, real -rejection followed by acceptance, and collection roots. - -Each paired fixture runs with single-instruction budgets and twice with full -budgets, comparing exact result bits or faults, intrinsic charges and total -cycles. Explicit source `as long` conversions are charged separately. The GC -fixture reuses the existing test-only FRAME_SYNC marker hook; all allocations, -roots and post-collection draws are compiled PBS. At least 1,100 discarded Random -objects are reclaimed while array, field and closure references preserve the -same generator. The import fixture uses the production workspace builder and -lifecycle assembler. The focused driver calls file initializers before Probe.main; -it does not claim a new lifecycle API. - -```sh -./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeRandomTest' -python3 tools/pbx-conformance/run.py --runtime ../runtime --random-only -python3 tools/pbx-conformance/run.py --runtime ../runtime --random-only --release -``` - -The driver rejects an oracle copy that differs from the selected provider and -prints source/oracle/catalog/lockfile fingerprints and toolchain/profile details. -A complete run includes the Random corpus and keeps it separate from the older -114 input/type fixtures. Rare synthetic 64-attempt acceptance/cap/rollback, -malformed carriers and native provenance are provider tests, not PBS-produced -claims. Qualify those separately with the provider's `random_contract` suite and -`cargo test -p prometeu-vm --lib random` in debug/release. No alternate RNG or -public injection hook is used. Installed knowledge validation remains a separate -gate for packaged SDK/spec/example resources. - -## PBS generic contracts - -`PbsGenericContractsTest` generates fourteen mandatory source fixtures: -`identity`, `manual`, `multiple`, `tuple`, `optional`, `function`, `contract`, -`native`, `recursive`, `phantom`, `receiver`, `gc`, `installed` and `imports`. -The corpus uses ordinary concrete Trait descriptors on the existing runtime. -It checks several applications on one owner, ordered substitution, composed -multi-slot values, finite recursion, canonical aliases/reexports and distinct -same-named argument declarations. The imported program uses the production -workspace builder and lifecycle assembler. - -The generic and handwritten concrete identity fixtures both execute with one -heap handle, establishing that contract adaptation needs no generic wrapper. -Typed absence and implementation index zero are valid. A mismatched Trait call -must be rejected by the verifier or trap with the runtime type check. The GC -fixture retains a contract receiver through a closure while at least 1,100 -discarded objects are reclaimed. Reduced GuestBytes, HandleSlots and loader -implementation limits verify refusal and ownership release. Descriptor counts -and PBX byte sizes are printed as evidence, without a performance threshold. - -```sh -./gradlew :prometeu-architecture-tests:test --tests '*PbsGenericContractsTest' -python3 tools/pbx-conformance/run.py --runtime ../runtime --generic-contracts-only -``` - -The full harness also requires these fixtures. The driver uses an external -runtime checkout without editing its sources or changing PBX, ISA or quotas. - - -## Minimal storage ISA, SDK collections and phase-aware refusals - -Generate common/source fixtures and the real installed-JAR examples, then run: - -```sh -./gradlew :prometeu-compiler:prometeu-build-pipeline:test :prometeu-architecture-tests:test :prometeu-app:installedKnowledgeTest -CARGO_TARGET_DIR=/tmp/studio-pbx-conformance python3 tools/pbx-conformance/run.py --runtime ../runtime -CARGO_TARGET_DIR=/tmp/studio-pbx-conformance python3 tools/pbx-conformance/run.py --runtime ../runtime --release -``` - -Focused `--list-cursor-only` and `--linked-only` modes include mandatory neutral -storage/copy/terminal/admission fixtures as well as their collection corpus. The -complete run requires both. No runtime source, manifest, lockfile or target -artifact is modified: the Cargo harness and target live outside that checkout. - -The selected provider supports ARRAY_LEN and ARRAY_COPY, ordinary typed stores -and terminal TRAP. Four dead-code fixtures prove that 0xA7/0xA8/0xAA/0xAB reject -at real instruction positions; corresponding Int32-immediate fixtures must load. -All producer-opcode checks decode instruction boundaries rather than scanning -raw PBX bytes. Neutral ordinary/optimized programs qualify stores and copy without -PBS types. A store followed by TRAP_EXPLICIT proves that terminal failure retains -previous effects and source spans survive lowering/optimization. - -Eleven paired neutral copy cases independently check scalar/vec2/String groups, -snapshot overlap, empty ranges, bad ranges/receivers, negative/above-u32 counts -and fault precedence. At the actual copy PC, zero budget executes nothing; -positive budget admits a complete attempt with overshoot. N=10/W=1 costs 24, -including receiver/range/scratch refusal; W=2 costs 44. Invalid or empty counts -cost base 4 as defined by the provider. Refusals preserve the five operands and -previous storage, release scratch and do not count a successful step. Native -String owners release with the session. Checked cost-overflow defenses requiring -synthetic internal widths are provider evidence, not an assertion that admitted -consumer layouts can attain those widths. - -List source fixtures cover every mutator, exact growth, logical versus physical -bounds, int/long and named evaluation, holes, aliases and complete native/tuple/ -Fn/contract/reference groups. Linked fixtures cover empty/single/multiple states, -reciprocal links, nearest-end lookup, complete values and both snapshot orders. -Logical SDK refusals now produce TRAP_EXPLICIT; physical instructions retain -their own faults. No missing ordinary or optimized fixture is silently skipped. - -Four List and ten Linked source-generated mutation boundaries have normal and -optimized variants. GuestBytes, HandleSlots, AuxiliaryBytes and TemporaryBytes -ceilings are lowered from measured setup/success peaks. Non-owning diagnostic -observations inspect the original collection objects independently of guest code. -Every instruction prefix is compared with the corresponding successful prefix. -A refused instruction preserves its own observable entry state. Before visible -mutation the entire old collection must remain unchanged; after mutation the -previous successful writes remain, without a whole-method rollback or safe-reuse -claim. Successful single-instruction-budget traversal also qualifies suspension -and resumption in the middle of a source method. Snapshot capture failures must -always preserve their source and expose no partial result. - -No-growth insertion prepares a one-slot private array before shifting and copies -that complete stored group into place; candidate/optional/result and operand/ -frame preparation remain charged. ARRAY_COPY scratch remains a mandatory observed -refusal. Linked prepares nodes/results before its sequential link updates. The -corpus retains explicit coverage requirements for these resource refusal paths; -it does not rename old publication guarantees as new evidence. - -Normal GC safepoints qualify removed nodes and payloads, collection clear, -snapshot independence, consumed-prefix reclamation and sticky final values. -The Cursor fixture requires 1,200 -> 1 -> 1 -> 0 snapshot nodes/payloads, with no -live source/snapshot array. Linked captures must not retain editable source nodes. -The actual installed SDK/spec/example is compiled outside the checkout and its -PBX is loaded/executed by the production VM; import/reexport fixtures also run. - -Catalog schema 2 is imported with all 25 fields, per-entry nullable masks, -explicit invocation/scratch/context profiles and cost parameters. Ordinary parity -and rejection tests need no runtime checkout. Explicit exporter verification uses -`tools/runtime-catalog/verify.py` and the selected clean SHA/digests. Nullable -hash.string metadata is qualified independently of older non-nullable String -entries; importing it does not deliver PBS hashing facades or Set/Map. - -Evidence prints consumer/provider source hashes, selected revision and clean state, -toolchain/platform/profile, lockfile/catalog hashes, capabilities, default ceilings -and lowered refusal limits. Keep new qualification separate from historical List/ -Linked evidence; prior successful providers are not relabeled as the new target. - -## PBS hashing, Identity and Set - -`IdentityHashingPipelineTest` qualifies neutral 0x97/0x98 production, complete -concrete/Trait groups and both optimizer paths. It also emits malformed-category, -right-TypeId, unknown-TypeId, dead-code, partial-group and truncated fixtures. -Unknown global inputs in two neutral cases reach production runtime validation: -an absent/different left cannot hide the invalid complete right view. Refusal -retains all three input slots, charges seven cycles and executes zero successful -query steps; zero budget executes nothing. - -`PbsIdentityHashingTest` selects all 30 scalar/String rows from the unchanged -118-row independent provider C XXH64 oracle. Both producer paths preserve exact -signed digest bits and attempted costs. Separate source fixtures qualify Struct, -Array, Fn, Random, complete contracts, mutation, aliases and discarded scalar and -reference results. The reference-query source gate ran before Set algorithm work. -The consumer oracle copy is checked against the selected provider on every -explicit harness invocation. Ordinary Gradle compilation uses local resources. - -`PbsSetTest` exercises the complete source API, contextual/default/explicit -construction, optional/default diagnostics, nominal origin, shared complete values, -content opt-in, collisions, exact growth arithmetic, callbacks, aliases and Cursor. -Counter strategies demonstrate that rehash and capture do not call hash/equals. -SDK aliases, generic-function reexports and installed examples compile through -actual workspace builders; installed compilation uses only installDist JARs in an -external directory and writes mandatory PBX fixtures for runtime execution. - -```sh -./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*IdentityHashingPipelineTest' -./gradlew :prometeu-architecture-tests:test --tests '*PbsIdentityHashingTest' --tests '*PbsSetTest' -./gradlew :prometeu-app:installedKnowledgeTest -CARGO_TARGET_DIR=/tmp/studio-pbx-target python3 tools/pbx-conformance/run.py --runtime ../runtime --identity-hashing-only -CARGO_TARGET_DIR=/tmp/studio-pbx-target python3 tools/pbx-conformance/run.py --runtime ../runtime --set-only -``` - -The Set quota corpus measures old/candidate coexistence and compares every -original-object instruction prefix with a successful run. It treats guard writes -separately from structural writes. Natural quota cases cover insertion, growth, -duplicate inclusion, removal, clear and capture with no claim that all failures -preserve the entire Set or that every theoretical failure boundary occurs at the -sampled limits. Current natural runs refuse before structural mutation; this is -reported explicitly by their summaries. - -A **separate test-only instrumented source fixture** inserts a controlled Array -allocation after the real candidate-table store and before size assignment. A -lowered guest quota refuses that probe. The old size six, new table capacity 16, -seven reachable nodes and active guard remain, while the refused instruction -preserves its own entry state. This demonstrates the post-publication failure -boundary; it is not a production SDK allocation, callback, algorithm or claim about -natural refusal frequency. Its ordinary/optimized fixtures are named -`pbs-set-injected-refusal-growth*` and are generated from an in-memory SDK copy. - -Real safepoints qualify source Set node/candidate release, removal/clear, snapshot -prefix reclamation and sticky final retention. Set GC tests do not assume an -iteration order. Add `--release` to qualify the Rust release profile independently -of the two producer variants; omit focused flags for the complete mandatory corpus. -All harness builds remain outside the runtime checkout, which is consumed unchanged. - -## PBS Stack and Queue qualification - -The mandatory Stack/Queue corpus is included in every complete run. A focused -run uses `python3 tools/pbx-conformance/run.py --runtime ../runtime --stack-queue-only`; -add `--release` for the optimized runtime profile. Both source producer paths are -mandatory in each profile. Generate fixtures with the architecture tests and -`:prometeu-app:installedKnowledgeTest` before executing the runner. - -`stack_queue.rs` validates dense/circular storage, inactive-slot cleanup, exact -capacity/growth, wrapped growth, complete payloads, once/named evaluation, snapshot -orders/states, imports and actual installed-JAR examples. Lowered quota runs compare -complete original-object instruction prefixes to a successful run and distinguish -preservation before mutation from retained writes afterward. Separate test-only -growth probes demonstrate an installed candidate with old size after a later fault; -these probes are not shipped or counted as natural refusal frequencies. - -GC fixtures require actual advancing collection counters. Snapshots release source -backings and observe 1,200 → 1 → 1 → 0 nodes/payloads. Collection fixtures observe -64 → 61 → 0 → 1 → 0 payloads and only one retained backing until its final owner -is dropped. Temporary Cargo projects/targets stay outside the runtime checkout. - - -## PBS Result, Sprite and Animation qualification - -Generate the source corpora with `:prometeu-architecture-tests:test` and -`:prometeu-app:installedKnowledgeTest`. Focused native gates are `--result-only` -and `--animation-only`; add `--release` for the runtime release profile. Before -animation qualification, generate the Composer pixel corpus with -`:prometeu-app:headlessProcessTest --tests '*AnimationInstalledRuntimeTest'` -and `-PstudioRuntimeInstall=`. The desktop gate -is `:prometeu-app:animationDesktopTest`. Each native gate -requires both ordinary and optimized producer variants and fails on missing fixtures. - -Result executes status plus complete payload groups, once-only propagation and -handling, error remapping, reference/Fn/trait/builtin payloads and uncaught traps. -Animation executes the public core, reusable independent backing, state/reset/time -boundaries, every domain error, exact long limits and a test-only near-limit state. -The isolated count/phase setup is never shipped as a public mutation hook. - -`animation.rs` single-steps actual instructions between post-construction markers. -Sprite and successful, negative and overflow advance paths must execute zero -StructNew/ArrayNew/MakeClosure instructions. Large jumps must remain below the -bounded instruction gate. Zero guest/handle quotas trap during construction and -are distinct from recoverable domain errors. A test-only safepoint marker observes -live private rings followed by complete reclamation after their last owner clears. - -The installed-JAR producer saves a real Packer-bound canonical sidecar, compiles -virtual factories with read-only JSON origins and supplies both producer variants -for production firmware execution. `AnimationInstalledRuntimeTest` separately boots -the configured extracted runtime and compares every pixel of direct/generated -Composer sprites with the shared preview across tick boundaries and alternating -palettes. That saved-project corpus is replayed by production firmware in native -dev/release with both producers, comparing the exact same canonical pixels. The public Composer -facade retains int status and nine arguments; its private host carrier is narrowed -from the existing native Int64 status. No runtime source write is required. - -Keep Cargo targets in `/tmp` and retain source hashes, provider revision, profiles, -allocation counts and GC observations with the completed discussion's evidence. diff --git a/tools/pbx-conformance/animation.rs b/tools/pbx-conformance/animation.rs deleted file mode 100644 index e974b209..00000000 --- a/tools/pbx-conformance/animation.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Real core playback and executed allocation evidence, including error paths. -use super::*; -use prometeu_vm::LogicalFrameEndingReason as End; -use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op}; - -pub fn verify(root: &std::path::Path) { - let manifest = std::fs::read_to_string(root.join("pbs-animation-manifest.txt")).expect("mandatory animation manifest"); - let names: Vec<_> = manifest.lines().collect(); - assert_eq!(names, ["basic", "loop", "once", "negative", "overflow", "draft", "limits", "matrix", "errors"]); - for name in names { for suffix in ["", "-optimized"] { - let bytes = std::fs::read(root.join(format!("pbs-animation-{name}{suffix}.pbx"))).expect("mandatory animation fixture"); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|e| panic!("animation/{name}{suffix}: load {e:?}")); - let mut vm = VirtualMachine::from_image(image.clone(), Default::default()); - vm.prepare_boot_call().unwrap(); - let mut watching = false; let mut started = 0; let mut ended = 0; let mut allocations = 0; let mut measured_steps=0; - for step in 0..2_000_000 { - let instruction = decode_next(vm.pc(), image.code()).unwrap(); - if instruction.opcode == Op::PushI32 { - if instruction.imm_i32().unwrap() == 162000001 { watching = true; started += 1; } - if instruction.imm_i32().unwrap() == 162000002 { watching = false; ended += 1; } - } - if watching { measured_steps+=1; } - if watching && matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; } - let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None)) - .unwrap_or_else(|e| panic!("animation/{name}{suffix}: run {e:?}")); - if matches!(report.reason, End::Halted | End::EndOfRom) { break; } - assert!(matches!(report.reason, End::BudgetExhausted), "animation/{name}{suffix}: {report:?}"); - assert!(step < 1_999_999, "animation failed to terminate"); - } - assert_eq!(vm.operand_stack_top(2), vec![Value::Int32(42), Value::Int32(0)], "animation/{name}{suffix}"); - if !matches!(name, "basic" | "draft" | "limits" | "matrix") { assert_eq!((started, ended), (1, 1)); } - assert!(measured_steps<50000,"bounded frame traversal: {measured_steps}"); - assert_eq!(allocations, 0, "animation/{name}{suffix}: executed advance/sprite heap allocations"); - if name=="basic" { - use prometeu_vm::resource_budget::{RuntimeLimits,RuntimeResource}; - for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots] { - let mut refused=VirtualMachine::from_image(image.clone(),RuntimeLimits::default().lowered(resource,0).unwrap()); - refused.prepare_boot_call().unwrap();let report=refused.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::Trap(ref fault) if fault.code==prometeu_bytecode::TRAP_RESOURCE_LIMIT)); - assert_eq!(refused.heap().len(),0);println!("ANIMATION QUOTA TRAP PASS {suffix} {resource:?}"); - } - } - println!("ANIMATION PASS {name}{suffix} watched={started} executed_allocations={allocations}"); - } } - verify_gc(root); - verify_installed(root); - verify_composer(root); -} - -fn verify_gc(root: &std::path::Path) { - for suffix in ["", "-optimized"] { - let bytes=std::fs::read(root.join(format!("pbs-animation-gc{suffix}.pbx"))).unwrap(); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap(); - for round in 0..2 { - let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::FrameSync),"animation GC: {report:?}"); - let objects=vm.heap().diagnostic_typed_storage(); - for name in ["Animator","_AnimationClip","_AnimationFrame"] { - let count=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count(); - if round==0 {assert!(count>0,"live animation root {name}");} else {assert_eq!(count,0,"unowned cycle {name}");} - } - assert!(vm.resource_snapshot().gc.reclaimed>1000); - println!("ANIMATION GC PASS {suffix} round={round} collections={} reclaimed={}",vm.resource_snapshot().gc.collections,vm.resource_snapshot().gc.reclaimed); - } - } -} - -fn verify_installed(root: &std::path::Path) { - use prometeu_drivers::TestPlatform; - use prometeu_firmware::firmware::Firmware; - use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource}}; - for suffix in ["", "-optimized"] { - let name=format!("pbs-animation-installed{suffix}"); - let mut fw=Firmware::new(None);let mut platform=TestPlatform::new(); - fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game,capabilities:caps::NONE,memcard_slots:None,program:std::fs::read(root.join(format!("{name}.pbx"))).unwrap(),assets:AssetsPayloadSource::empty(),asset_table:vec![],preload:vec![]}); - for _ in 0..5 {fw.tick(&InputSignals::default(),&mut platform);assert!(fw.os.vm().last_crash_report().is_none());} - let task=fw.os.lifecycle().resident_game_task().unwrap();let mut sessions=fw.os.sessions();let session=sessions.vm_session_for_task_mut(task).unwrap(); - let id=std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap();session.vm.prepare_call(id.trim()).unwrap(); - let report=session.vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(session.vm.operand_stack_top(1),vec![Value::Int32(42)]); - println!("ANIMATION INSTALLED GENERATED/FIRMWARE PASS {suffix}"); - } -} - -fn verify_composer(root: &std::path::Path) { - use prometeu_drivers::TestPlatform; - use prometeu_firmware::firmware::Firmware; - use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource,AssetsPackPrelude}}; - for suffix in ["", "-optimized"] { - let prefix=format!("pbs-animation-composer{suffix}"); - let manifest:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.manifest.json"))).unwrap()).unwrap(); - let oracle:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.oracle.json"))).unwrap()).unwrap(); - let packed=std::fs::read(root.join(format!("{prefix}.assets.pa"))).unwrap();let prelude=AssetsPackPrelude::from_bytes(&packed).unwrap(); - let mut fw=Firmware::new(None);let mut platform=TestPlatform::new(); - fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation Composer".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game, - capabilities:caps::COMPOSER,memcard_slots:None, - program:std::fs::read(root.join(format!("{prefix}.pbx"))).unwrap(),assets:AssetsPayloadSource::from_bytes(packed[prelude.payload_offset as usize..].to_vec()), - asset_table:serde_json::from_value(manifest["asset_table"].clone()).unwrap(),preload:serde_json::from_value(manifest["preload"].clone()).unwrap()}); - let mut observed=0; - for _ in 0..50000 { - fw.tick(&InputSignals::default(),&mut platform); - assert!(fw.os.vm().last_crash_report().is_none(),"Composer {suffix}: {:?}",fw.os.vm().last_crash_report()); - if let Some(task)=fw.os.lifecycle().resident_game_task() { - let completed={let sessions=fw.os.sessions();sessions.vm_session_for_task(task).map(|s|s.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed)).unwrap_or(0)}; - if completed>observed { - assert_eq!(completed,observed+1,"one native frame per observation"); - let sample=&oracle[observed as usize];let pixels=sample["rgba"].as_array().unwrap();let front=platform.local_hardware().gfx.front_buffer();let width=platform.local_hardware().gfx.size().0; - for x in [32,64] {for y in 0..16 {for dx in 0..16 {assert_eq!(front[(32+y)*width+x+dx],pixels[y*16+dx].as_u64().unwrap() as u32,"{prefix} tick={observed} x={x} pixel={dx},{y}");}}} - println!("ANIMATION COMPOSER PIXELS PASS {suffix} tick={observed} glyph={} palette={}",sample["glyph"],sample["palette"]); - observed=completed;if observed==8 {break;} - } - } - std::thread::yield_now(); - } - assert_eq!(observed,8,"native Composer did not produce all frames"); - } -} diff --git a/tools/pbx-conformance/lifecycle.rs b/tools/pbx-conformance/lifecycle.rs deleted file mode 100644 index 5e861fab..00000000 --- a/tools/pbx-conformance/lifecycle.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! Studio-produced PBS images through the production VM and foreground firmware. -use prometeu_bytecode::{Value, registry::LifecycleRole}; -use prometeu_drivers::TestPlatform; -use prometeu_firmware::firmware::{Firmware, FirmwareState}; -use prometeu_hal::{InputSignals, app_mode::AppMode, cartridge::{Cartridge, AssetsPayloadSource}}; -use prometeu_system::task::{TaskId, TaskState}; -use prometeu_vm::{HostContext, LogicalFrameEndingReason as Reason, ValidatedProgramImage, VirtualMachine}; -use std::path::Path; - -fn bytes(root: &Path, name: &str) -> Vec { - std::fs::read(root.join(format!("{name}.pbx"))).unwrap_or_else(|e| panic!("{name}: {e}")) -} -fn load(root: &Path, name: &str) -> VirtualMachine { - let image = ValidatedProgramImage::load(&bytes(root, name), &mut super::LoadBudget::new(Default::default()), super::caps::NONE).unwrap(); - for role in [LifecycleRole::BeforePause, LifecycleRole::BeforeResume] { - if let Some(id) = image.registry().lifecycle_hook(role) { assert_ne!(id.0, 0); } - } - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, Reason::EndOfRom | Reason::Halted), "{name}: {report:?}"); - vm -} -fn query(root: &Path, name: &str, vm: &mut VirtualMachine) -> i32 { - let id = std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap(); - vm.prepare_call(id.trim()).unwrap(); - let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, Reason::EndOfRom | Reason::Halted), "{name}: {report:?}"); - match vm.operand_stack_top(1)[0] { Value::Int32(value) => value, ref other => panic!("{other:?}") } -} -fn finish_hook(vm: &mut VirtualMachine, expected: Reason) -> usize { - let mut previous = vm.lifecycle_remaining_cycles().unwrap(); - let mut slices = 0; - loop { - slices += 1; assert!(slices < 16); - let report = vm.run_budget(u64::MAX, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - // Includes the specified whole-instruction overshoot; this corpus uses scalar instructions. - assert!(report.cycles_used <= VirtualMachine::LIFECYCLE_SLICE + 100); - if report.reason != Reason::BudgetExhausted { - assert_eq!(report.reason, expected); break; - } - let remaining = vm.lifecycle_remaining_cycles().unwrap(); - assert!(remaining < previous); - assert_eq!(previous.saturating_sub(report.cycles_used), remaining); - previous = remaining; - } - slices -} - -fn snapshot(fw: &mut Firmware, task: TaskId) -> (usize, u64, u64) { - // The active foreground facade switches to the crash UI after failure. - // Observe the retained game session so a foreground change cannot reset the oracle. - let sessions = fw.os.sessions(); - let session = sessions.vm_session_for_task(task).unwrap(); - (session.vm.pc(), session.runtime.tick_index, - session.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed) as u64) -} -fn firmware(root: &Path, name: &str) -> (Firmware, TestPlatform, TaskId) { - let mut fw = Firmware::new(None); let mut platform = TestPlatform::new(); - fw.load_cartridge(Cartridge { - app_id: 86, title: "Studio PBS lifecycle".into(), app_version: "1.0.0".into(), - app_mode: AppMode::Game, capabilities: super::caps::NONE, memcard_slots: None, - program: bytes(root, name), assets: AssetsPayloadSource::empty(), asset_table: vec![], preload: vec![], - }); - fw.tick(&InputSignals::default(), &mut platform); - let task = fw.os.lifecycle().resident_game_task().unwrap(); - fw.tick(&InputSignals::default(), &mut platform); - assert!(fw.os.vm().last_crash_report().is_none()); - (fw, platform, task) -} -fn foreground_case(root: &Path, name: &str, expected: i32, resume: bool) { - let (mut fw, mut platform, task) = firmware(root, name); - let signals = InputSignals::default(); - fw.request_home_from_host(); - fw.tick(&signals, &mut platform); // Existing Home handoff, including its gameplay reaction. - let suspended = snapshot(&mut fw, task); - fw.tick(&signals, &mut platform); // Hook only, or already-suspended case without a hook. - assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended), "{name}"); - assert_eq!(snapshot(&mut fw, task), suspended, "pause changed gameplay state: {name}"); - assert!(fw.resume_resident_game_from_home()); - if resume { - fw.tick(&signals, &mut platform); // BeforeResume only. - assert_eq!(snapshot(&mut fw, task), suspended, "resume changed gameplay state: {name}"); - } - fw.tick(&signals, &mut platform); // First eligible gameplay frame validates guest stage/init/heap. - assert!(fw.os.vm().last_crash_report().is_none(), "{name}"); - assert_eq!(snapshot(&mut fw, task).1, suspended.1 + 1); - let actual = { - let mut sessions = fw.os.sessions(); - let session = sessions.vm_session_for_task_mut(task).unwrap(); - // Terminal observation only, after all continuation/frame assertions; no later host tick. - query(root, name, &mut session.vm) - }; - assert_eq!(actual, expected, "ordered guest effects/init/heap: {name}"); - println!("FIRMWARE HOME/RESUME PASS {name}: pc={}, gameplayTicks={}, frames={}, guest={actual}", suspended.0, suspended.1, suspended.2); -} - -fn other_foreground_paths(root: &Path, name: &str) { - for shell in [false, true] { - let (mut fw, mut platform, task) = firmware(root, name); - let before = snapshot(&mut fw, task); - if shell { fw.os.sessions().try_create_native_shell_task(99, "Tools").unwrap(); } - else { fw.os.lifecycle().suspend_task(task).unwrap(); } - fw.tick(&InputSignals::default(), &mut platform); - assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended)); - assert_eq!(snapshot(&mut fw, task), before); - println!("DIRECT/SHELL SUSPEND PASS {name}: shell={shell}, no reaction tick"); - } - let mut vm = load(root, name); - vm.prepare_boot_call().unwrap(); - let partial = vm.run_budget(1, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert_eq!(partial.reason, Reason::BudgetExhausted); - assert!(!vm.call_stack_is_empty()); - let pc = vm.pc(); let stack = vm.operand_stack_top(1000).to_vec(); - assert!(!stack.is_empty(), "suspended wrapper must retain an operand"); - for role in [LifecycleRole::BeforePause, LifecycleRole::BeforeResume] { - assert!(vm.begin_lifecycle(role).unwrap()); - finish_hook(&mut vm, Reason::LifecycleComplete); - assert_eq!(vm.pc(), pc); assert_eq!(vm.operand_stack_top(1000).to_vec(), stack); - assert!(!vm.call_stack_is_empty()); - } - let resumed = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(resumed.reason, Reason::EndOfRom | Reason::Halted)); - assert_eq!(query(root, name, &mut vm), 230112); - println!("SUSPENDED STACK/CONTINUATION PASS {name}: retained operand, frame and heap"); -} - -pub fn verify(root: &Path) { - for suffix in ["", "-optimized"] { - for (case, expected, resume) in [("both", 230112, true), ("pause", 20109, false), ("resume", 30110, true), ("none", 107, false)] { - let name = format!("pbs-lifecycle-{case}{suffix}"); - let mut vm = load(root, &name); - for (role, present) in [(LifecycleRole::BeforePause, case == "both" || case == "pause"), (LifecycleRole::BeforeResume, resume)] { - let pc = vm.pc(); let stack = vm.operand_stack_top(1000).to_vec(); - assert_eq!(vm.begin_lifecycle(role).unwrap(), present); - if present { - assert!(vm.begin_lifecycle(role).is_err(), "controlled calls cannot reenter"); - finish_hook(&mut vm, Reason::LifecycleComplete); - } - assert_eq!(vm.pc(), pc); assert_eq!(vm.operand_stack_top(1000).to_vec(), stack); - } - vm.prepare_boot_call().unwrap(); - let next = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(next.reason, Reason::Halted | Reason::EndOfRom)); - assert_eq!(query(root, &name, &mut vm), expected); - foreground_case(root, &name, expected, resume); - } - other_foreground_paths(root, &format!("pbs-lifecycle-both{suffix}")); - let name = format!("pbs-lifecycle-direct{suffix}"); - let mut vm = load(root, &name); - assert!(!vm.lifecycle_active()); assert_eq!(query(root, &name, &mut vm), 230112); - println!("ORDINARY CALL PASS {name}: no controlled invocation"); - - let name = format!("pbs-lifecycle-slices{suffix}"); - let mut vm = load(root, &name); - vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap(); - let hook_pc = vm.pc(); vm.insert_breakpoint(hook_pc); - let remaining = vm.lifecycle_remaining_cycles(); - let stopped = vm.run_budget(250_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert_eq!(stopped.reason, Reason::Breakpoint); assert_eq!(stopped.cycles_used, 0); - assert_eq!(vm.lifecycle_remaining_cycles(), remaining); - vm.remove_breakpoint(hook_pc); - vm.step(&mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert!(vm.lifecycle_remaining_cycles().unwrap() < remaining.unwrap()); - assert!(finish_hook(&mut vm, Reason::LifecycleComplete) > 1); - println!("SLICES + DEBUGGER PASS {name}: one retained total fuel budget"); - - for case in ["trap", "fuel"] { - let name = format!("pbs-lifecycle-{case}{suffix}"); - let mut vm = load(root, &name); - vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap(); - let mut slices = 0; - let terminal = loop { - slices += 1; assert!(slices < 16); - let report = vm.run_budget(u64::MAX, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - if report.reason != Reason::BudgetExhausted { break report.reason; } - }; - if case == "trap" { assert!(matches!(terminal, Reason::Trap(_))); } - else { assert!(matches!(&terminal, Reason::Panic(text) if text.contains("lifecycle total cycle budget exhausted"))); assert!(slices > 1); } - let blocked = vm.run_budget(1000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert_eq!(blocked.reason, terminal); assert_eq!(blocked.steps_executed, 0); - assert!(vm.prepare_boot_call().is_err()); - let (mut fw, mut platform, task) = firmware(root, &name); - fw.request_home_from_host(); fw.tick(&InputSignals::default(), &mut platform); - let before = snapshot(&mut fw, task); - for _ in 0..16 { - fw.tick(&InputSignals::default(), &mut platform); - if matches!(fw.state, FirmwareState::AppCrashes(_)) { break; } - } - assert!(matches!(fw.state, FirmwareState::AppCrashes(_)), "{name}"); - assert_eq!(snapshot(&mut fw, task).1, before.1); - assert_eq!(snapshot(&mut fw, task).2, before.2); - println!("FATAL + GAMEPLAY BLOCK PASS {name}: {terminal:?}, slices={slices}"); - } - } - // These binaries are explicitly synthetic; no PBS sync surface is claimed. - for case in ["direct", "transitive"] { - let name = format!("synthetic-lifecycle-sync-{case}"); - let mut vm = load(root, &name); - vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap(); - let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, Reason::Trap(_)), "{report:?}"); - let again = vm.run_budget(1000, &mut super::NoNative, &mut HostContext::new(None)).unwrap(); - assert_eq!(again.steps_executed, 0); assert_eq!(again.reason, report.reason); - let (mut fw, mut platform, task) = firmware(root, &name); - fw.request_home_from_host(); fw.tick(&InputSignals::default(), &mut platform); - let before = snapshot(&mut fw, task); - fw.tick(&InputSignals::default(), &mut platform); - assert!(matches!(fw.state, FirmwareState::AppCrashes(_))); - assert_eq!(snapshot(&mut fw, task).1, before.1); assert_eq!(snapshot(&mut fw, task).2, before.2); - println!("SYNTHETIC SYNC REJECTION PASS {case}: no gameplay/frame publication"); - } - let name = "pbs-lifecycle-imports"; - let mut vm = load(root, name); - assert!(vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap()); - finish_hook(&mut vm, Reason::LifecycleComplete); - assert!(!vm.has_lifecycle_hook(LifecycleRole::BeforeResume)); - println!("PRODUCTION PIPELINE IMPORTS PASS: alias/reexport selected one original hook"); -} diff --git a/tools/pbx-conformance/main.rs b/tools/pbx-conformance/main.rs deleted file mode 100644 index a049e298..00000000 --- a/tools/pbx-conformance/main.rs +++ /dev/null @@ -1,2085 +0,0 @@ -use prometeu_bytecode::Value; -mod stack_queue; -mod lifecycle; -mod memcard; -mod result; -mod animation; -use prometeu_bytecode::load_limits::{LoadBudget, LoadLimits}; -use prometeu_hal::syscalls::caps; -use prometeu_vm::{ - HostContext, HostReturn, NativeInterface, ValidatedProgramImage, VirtualMachine, -}; - -struct HasCart(usize); -impl NativeInterface for HasCart { - fn syscall( - &mut self, - id: u32, - args: &[Value], - ret: &mut HostReturn, - _: &mut HostContext, - ) -> Result<(), prometeu_hal::vm_fault::VmFault> { - assert_eq!(id, 1); - assert!(args.is_empty()); - self.0 += 1; - ret.push_bool(false); - Ok(()) - } -} -struct NoNative; -impl NativeInterface for NoNative { - fn syscall( - &mut self, - _: u32, - _: &[Value], - _: &mut HostReturn, - _: &mut HostContext, - ) -> Result<(), prometeu_hal::vm_fault::VmFault> { - panic!("fixture unexpectedly invoked native code") - } -} - -fn main() { - let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory")); - use prometeu_vm::resource_budget::{RuntimeLimits,RuntimeResource as Q}; - let limits=RuntimeLimits::default(); - for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations,Q::IndividualStringBytes,Q::CallDepth] { - println!("DEFAULT VM LIMIT {resource:?}={}",limits.get(resource)); - } - if std::env::args().any(|arg| arg == "--animation-only") { animation::verify(&root); return; } - if std::env::args().any(|arg| arg == "--result-only") { result::verify(&root); return; } - if std::env::args().any(|arg| arg == "--memcard-only") { memcard::verify(&root); return; } - if std::env::args().any(|arg| arg == "--lifecycle-only") { lifecycle::verify(&root); return; } - if std::env::args().any(|arg| arg == "--stack-queue-only") { stack_queue::verify(&root); return; } - if std::env::args().any(|arg| arg == "--map-only") { verify_pbs_map_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--set-only") { verify_pbs_set_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--identity-hashing-only") { verify_identity_hashing_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--linked-only") { verify_common_storage_fixtures(&root); verify_pbs_linked_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--list-cursor-only") { verify_common_storage_fixtures(&root); verify_pbs_list_cursor_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--generic-contracts-only") { verify_pbs_generic_contract_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--generic-structs-only") { verify_pbs_generic_struct_fixtures(&root); return; } - if std::env::args().any(|arg| arg == "--random-only") { verify_pbs_random_fixtures(&root); return; } - verify_pbs_math_fixtures(&root); - if std::env::args().any(|arg| arg == "--math-only") { return; } - result::verify(&root); - animation::verify(&root); - verify_pbs_random_fixtures(&root); - verify_identity_hashing_fixtures(&root); - verify_catalog_fixtures(&root); - verify_pbs_fixtures(&root); - verify_pbs_structured_fixtures(&root); - verify_pbs_generic_contract_fixtures(&root); - verify_pbs_generic_struct_fixtures(&root); - verify_common_storage_fixtures(&root); - verify_pbs_list_cursor_fixtures(&root); - verify_pbs_linked_fixtures(&root); - verify_pbs_set_fixtures(&root); - verify_pbs_map_fixtures(&root); - stack_queue::verify(&root); - lifecycle::verify(&root); - verify_pbs_resource_refusals(&root); - verify_pbs_closure_frames(&root); - for name in [ - "minimal", - "jump-end", - "vec2-signature", - "closure-capture", - "trait-call", - "array-dynamic", - "common-pipeline", - "roles", - "join", - "memcard-role", - "intrinsic-dot", - ] { - let bytes = std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); - let image = ValidatedProgramImage::load( - &bytes, - &mut LoadBudget::new(LoadLimits::default()), - caps::NONE, - ) - .unwrap_or_else(|e| panic!("{name}: {e:?}")); - println!("LOAD PASS {name}"); - if name != "vec2-signature" { - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm - .run_budget(1000, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - let reason = format!("{:?}", report.reason); - assert!( - reason == "Halted" || reason == "EndOfRom", - "{name}: {report:?}" - ); - if name == "closure-capture" || name == "trait-call" { - assert!(matches!(vm.operand_stack_top(1)[0], Value::Int32(42))); - } - if name == "intrinsic-dot" { - assert!( - matches!(vm.operand_stack_top(1)[0], Value::Float(value) if value.to_bits() == 11f64.to_bits()) - ); - } - if name == "array-dynamic" { - assert!(matches!(vm.operand_stack_top(1)[0], Value::Int32(0))); - } - println!( - "EXEC PASS {name}: {reason}, {} steps", - report.steps_executed - ); - } - } - for name in ["native", "unknown-native", "native-abi", "unused-native"] { - let bytes = std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); - if name == "native" { - let image = ValidatedProgramImage::load( - &bytes, - &mut LoadBudget::new(LoadLimits::default()), - caps::SYSTEM, - ) - .unwrap(); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let mut native = HasCart(0); - let report = vm - .run_budget(1000, &mut native, &mut HostContext::new(None)) - .unwrap(); - assert_eq!(native.0, 1); - assert_eq!(format!("{:?}", report.reason), "Halted"); - println!("BIND + EXEC PASS native with SYSTEM"); - } - let capabilities = if name == "native" { - caps::NONE - } else { - caps::SYSTEM - }; - let error = ValidatedProgramImage::load( - &bytes, - &mut LoadBudget::new(LoadLimits::default()), - capabilities, - ) - .unwrap_err(); - record_fault(&root, name, error); - } - let baseline = std::fs::read(root.join("minimal.pbx")).unwrap(); - for (name, offset, value) in [ - ("version", 4, 1), - ("unsupported-section", 116, 9), - ("unknown-builtin", 178, 0), - ("invalid-role", 136, 4), - ("retired-opcode", 162, 0x54), - ] { - let mut bytes = baseline.clone(); - bytes[offset] = value; - reject(&root, name, &bytes, LoadLimits::default()); - } - for (name, code, max) in [ - ("raw-syscall", vec![0x70, 0, 1, 0, 0, 0, 1, 0], 0), - ("hostcall-index", vec![0x71, 0, 0, 0, 0, 0, 1, 0], 0), - ( - "retired-spawn", - vec![0x54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], - 0, - ), - ("retired-yield", vec![0x55, 0, 1, 0], 0), - ("retired-sleep", vec![0x56, 0, 0, 0, 0, 0, 1, 0], 0), - ( - "unreachable-reference", - vec![1, 0, 0x50, 0, 255, 255, 255, 255], - 0, - ), - ( - "nonfinite", - vec![1, 0, 0x15, 0, 0, 0, 0, 0, 0, 0, 0xf0, 0x7f], - 0, - ), - ("jump-immediate", vec![2, 0, 3, 0, 0, 0, 1, 0], 0), - ("zero-max", vec![0x17, 0, 0, 0, 0, 0, 1, 0], 0), - ("return-height", vec![0x17, 0, 0, 0, 0, 0, 0x51, 0], 1), - ("fallthrough", vec![0, 0], 0), - ] { - let mut functions = section(&baseline, 1).to_vec(); - functions[18..22].copy_from_slice(&(code.len() as u32).to_le_bytes()); - functions[26..30].copy_from_slice(&(max as u32).to_le_bytes()); - let bytes = replace(&replace(&baseline, 1, &functions), 2, &code); - reject(&root, name, &bytes, LoadLimits::default()); - } - // Two mutually recursive Array declarations: a structural cycle, with valid IDs. - reject( - &root, - "array-cycle", - &replace( - &baseline, - 6, - &[2, 0, 0, 0, 2, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0], - ), - LoadLimits::default(), - ); - reject( - &root, - "structural-cycle", - &replace( - &baseline, - 6, - &[ - 2, 0, 0, 0, 4, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, - ], - ), - LoadLimits::default(), - ); - reject( - &root, - "invalid-type-reference", - &replace(&baseline, 6, &[1, 0, 0, 0, 2, 0, 99, 0, 0, 0]), - LoadLimits::default(), - ); - reject( - &root, - "invalid-utf8", - &replace( - &baseline, - 6, - &[1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 255, 0x13, 0, 0, 0], - ), - LoadLimits::default(), - ); - reject( - &root, - "removed-input", - &replace(&baseline, 6, &[1, 0, 0, 0, 0, 0, 0, 1, 0, 0]), - LoadLimits::default(), - ); - let mut overlap = baseline.clone(); - overlap[36..40].copy_from_slice(&0u32.to_le_bytes()); - reject(&root, "overlap", &overlap, LoadLimits::default()); - reject( - &root, - "truncated", - &baseline[..baseline.len() - 1], - LoadLimits::default(), - ); - let mut duplicate = baseline.clone(); - duplicate[44..48].copy_from_slice(&0u32.to_le_bytes()); - reject( - &root, - "duplicate-section", - &duplicate, - LoadLimits::default(), - ); - reject( - &root, - "empty-entry", - &replace(&replace(&baseline, 1, &[0, 0, 0, 0]), 8, &[0, 0, 0, 0]), - LoadLimits::default(), - ); - reject( - &root, - "resource-types", - &baseline, - LoadLimits { - types: 0, - ..Default::default() - }, - ); - reject( - &root, - "resource-scratch", - &baseline, - LoadLimits { - temporary_bytes: 0, - ..Default::default() - }, - ); - reject( - &root, - "resource", - &baseline, - LoadLimits { - work: 0, - ..Default::default() - }, - ); -} - -fn verify_catalog_fixtures(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - let mut random_cycles = None; - for name in ["catalog-random-off", "catalog-random-on", "catalog-constants", "catalog-vec2-zero", "catalog-input", "catalog-string", "catalog-null-hash", "catalog-null-hash-optimized"] { - let bytes = std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|error| panic!("{name}: {error:?}")); - println!("LOAD PASS {name}"); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - if name == "catalog-input" { - assert!(matches!(report.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_UNAVAILABLE)); - println!("EXEC PASS {name}: TRAP_UNAVAILABLE (known query, no hardware)"); - continue; - } - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - if name.starts_with("catalog-random-") { - // Independent seed-42 vector and unit-range consumption from the provider handoff/tests. - assert_eq!(vm.operand_stack_top(3), vec![ - Value::Int64(0xF9090E529A7DAE00u64 as i64), Value::Int64(-7), - Value::Float(f64::from_bits(0x3FB304AA46C98538)), - ], "{name}: aliasing, discarded first next, mixed operations and exact order"); - if let Some(cycles) = random_cycles { assert_eq!(report.cycles_used, cycles, "optimization changed charged work"); } - random_cycles = Some(report.cycles_used); - } else if name == "catalog-vec2-zero" { - assert_eq!(vm.operand_stack_top(2), vec![Value::Float(0.0), Value::Float(0.0)]); - } else if name == "catalog-string" { - assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(0xAABBCCDD)]); - } else if name.starts_with("catalog-null-hash") { - assert_eq!(vm.operand_stack_top(1),vec![Value::Int64(0)],"provider null hash vector"); - use prometeu_bytecode::isa::core::CoreOpCode as Op; - assert_eq!(report.cycles_used,Op::PushConst.cycles()+8+Op::Halt.cycles()); - } else { - let mut constants: Vec<_> = prometeu_vm::builtin_constant_catalog().collect(); - constants.sort_by_key(|constant| constant.key.key()); - let mut expected = Vec::new(); - for constant in constants { expected.extend(constant.materialize().unwrap()); } - expected.reverse(); - let actual = vm.operand_stack_top(expected.len()); - assert_eq!(actual.len(), 16); - for (actual, expected) in actual.iter().zip(expected.iter()) { - match (actual, expected) { - (Value::Float(a), Value::Float(b)) => assert_eq!(a.to_bits(), b.to_bits()), - _ => assert_eq!(actual, expected), - } - } - } - println!("EXEC PASS {name}: {} cycles, {} steps", report.cycles_used, report.steps_executed); - } - let removed = std::fs::read(root.join("catalog-removed.pbx")).unwrap(); - reject(root, "catalog-removed", &removed, LoadLimits::default()); - let null_string = std::fs::read(root.join("catalog-null-string.pbx")).unwrap(); - reject(root, "catalog-null-string", &null_string, LoadLimits::default()); -} - -fn reject(root: &std::path::Path, name: &str, bytes: &[u8], limits: LoadLimits) { - let error = - ValidatedProgramImage::load(bytes, &mut LoadBudget::new(limits), caps::NONE).unwrap_err(); - record_fault(root, name, error); -} -fn record_fault(root: &std::path::Path, name: &str, error: prometeu_vm::VmInitError) { - if let prometeu_vm::VmInitError::RegistryLoadFailed(ref failure) = error { - let expected = match name { - "array-cycle" => Some("ArrayCycle"), - "structural-cycle" => Some("StructuralTypeCycle"), - "invalid-type-reference" => Some("TypeId"), - "invalid-utf8" => Some("Utf8"), - "removed-input" => Some("Builtin"), - "retired-spawn" | "retired-yield" | "retired-sleep" => Some("RemovedOpcode"), - "nonfinite" => Some("NonFiniteValue"), - "unreachable-reference" => Some("FunctionId"), - "return-height" => Some("ReturnHeight"), - "fallthrough" => Some("UnterminatedPath"), - "zero-max" => Some("StackOverflow"), - "duplicate-section" => Some("DuplicateSection"), - _ => None, - }; - if let Some(reason) = expected { - assert_eq!(format!("{:?}", failure.reason), reason, "{name}"); - } - } - let report = prometeu_system::CrashReport::VmInit { error }; - assert_eq!(report.pc(), None); - let fault = serde_json::json!({"kind":"vm_init", "pc":null, "summary":"Conformance fixture", "initError":report.init_diagnostic().unwrap()}); - let full: serde_json::Value = serde_json::from_slice( - &std::fs::read(std::env::args().nth(2).expect("schema path")).unwrap(), - ) - .unwrap(); - let schema = jsonschema::validator_for( - &serde_json::json!({"$defs":full["$defs"],"$ref":"#/$defs/fault"}), - ) - .unwrap(); - if !schema.is_valid(&fault) { - let reason = fault["initError"]["load"]["reason"].as_str().unwrap(); - assert!( - ["LifecycleRole", "NonFiniteValue"].contains(&reason), - "unexpected schema failure: {fault}" - ); - // Validate the ORIGINAL payload with only the observed missing enum value added. - // This is an explicit upstream defect report, not a claim of published-schema conformance. - let mut corrected = full.clone(); - corrected["$defs"]["loadFailure"]["properties"]["reason"]["enum"] - .as_array_mut() - .unwrap() - .push(serde_json::json!(reason)); - jsonschema::validator_for( - &serde_json::json!({"$defs":corrected["$defs"],"$ref":"#/$defs/fault"}), - ) - .unwrap() - .validate(&fault) - .unwrap(); - println!( - "UPSTREAM SCHEMA GAP: {reason} missing from published enum; original payload preserved" - ); - } - std::fs::write( - root.join(format!("fault-{name}.json")), - serde_json::to_vec_pretty(&fault).unwrap(), - ) - .unwrap(); - println!("REJECT PASS {name}: {}", fault["initError"]); -} - -fn word(bytes: &[u8], at: usize) -> usize { - u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) as usize -} -fn section(bytes: &[u8], kind: usize) -> &[u8] { - for i in 0..word(bytes, 8) { - let at = 32 + 12 * i; - if word(bytes, at) == kind { - let offset = word(bytes, at + 4); - return &bytes[offset..offset + word(bytes, at + 8)]; - } - } - panic!("missing section {kind}") -} -fn replace(bytes: &[u8], kind: usize, payload: &[u8]) -> Vec { - let count = word(bytes, 8); - let mut output = bytes[..32 + 12 * count].to_vec(); - for i in 0..count { - let at = 32 + 12 * i; - let body = if word(bytes, at) == kind { - payload - } else { - section(bytes, word(bytes, at)) - }; - let offset = output.len() as u32; - output[at + 4..at + 8].copy_from_slice(&offset.to_le_bytes()); - output[at + 8..at + 12].copy_from_slice(&(body.len() as u32).to_le_bytes()); - output.extend_from_slice(body); - } - output -} - -// Controlled provider boundary: every input read checks its identity and is counted. -struct PbsInput { - expected: usize, - reads: std::cell::Cell, - button: prometeu_hal::button::Button, -} -impl PbsInput { - fn read(&self, index: usize) -> &prometeu_hal::button::Button { - assert_eq!(index, self.expected, "PBS queried an unselected endpoint"); - self.reads.set(self.reads.get() + 1); - &self.button - } -} -impl prometeu_hal::PadBridge for PbsInput { - fn begin_frame(&mut self, _: &prometeu_hal::InputSignals) { unreachable!() } - fn any(&self) -> bool { unreachable!() } - fn up(&self) -> &prometeu_hal::button::Button { self.read(0) } - fn down(&self) -> &prometeu_hal::button::Button { self.read(1) } - fn left(&self) -> &prometeu_hal::button::Button { self.read(2) } - fn right(&self) -> &prometeu_hal::button::Button { self.read(3) } - fn a(&self) -> &prometeu_hal::button::Button { self.read(4) } - fn b(&self) -> &prometeu_hal::button::Button { self.read(5) } - fn x(&self) -> &prometeu_hal::button::Button { self.read(6) } - fn y(&self) -> &prometeu_hal::button::Button { self.read(7) } - fn l(&self) -> &prometeu_hal::button::Button { self.read(8) } - fn r(&self) -> &prometeu_hal::button::Button { self.read(9) } - fn start(&self) -> &prometeu_hal::button::Button { self.read(10) } - fn select(&self) -> &prometeu_hal::button::Button { self.read(11) } -} -impl prometeu_hal::TouchBridge for PbsInput { - fn begin_frame(&mut self, _: &prometeu_hal::InputSignals) { unreachable!() } - fn f(&self) -> &prometeu_hal::button::Button { self.read(12) } - fn x(&self) -> i32 { self.read(13); -123 } - fn y(&self) -> i32 { self.read(14); 456 } -} -impl prometeu_hal::InputPlatform for PbsInput { - fn pad(&self) -> &dyn prometeu_hal::PadBridge { self } - fn pad_mut(&mut self) -> &mut dyn prometeu_hal::PadBridge { self } - fn touch(&self) -> &dyn prometeu_hal::TouchBridge { self } - fn touch_mut(&mut self) -> &mut dyn prometeu_hal::TouchBridge { self } -} -impl prometeu_hal::RuntimePlatform for PbsInput { - fn input(&self) -> &dyn prometeu_hal::InputPlatform { self } - fn input_mut(&mut self) -> &mut dyn prometeu_hal::InputPlatform { self } - fn wall_clock(&self) -> &dyn prometeu_hal::WallClock { unreachable!("non-input platform access") } - fn render_submission_sink(&mut self) -> &mut dyn prometeu_hal::RenderSubmissionSink { unreachable!("non-input platform access") } - fn render_backend(&mut self) -> &mut dyn prometeu_hal::RenderBackend { unreachable!("non-input platform access") } - fn game2d_frame_composer(&mut self) -> &mut dyn prometeu_hal::Game2DFrameComposer { unreachable!("non-input platform access") } - fn audio(&self) -> &dyn prometeu_hal::AudioBridge { unreachable!("non-input platform access") } - fn audio_mut(&mut self) -> &mut dyn prometeu_hal::AudioBridge { unreachable!("non-input platform access") } - fn assets(&self) -> &dyn prometeu_hal::AssetBridge { unreachable!("non-input platform access") } - fn assets_mut(&mut self) -> &mut dyn prometeu_hal::AssetBridge { unreachable!("non-input platform access") } - fn telemetry(&self) -> &dyn prometeu_hal::TelemetryPlatform { unreachable!("non-input platform access") } -} -fn verify_pbs_fixtures(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - let buttons = ["up","down","left","right","a","b","x","y","l","r","start","select"]; - let mut count = 0; - let mut defaults_checked = std::collections::BTreeSet::new(); - for entry in std::fs::read_dir(root).unwrap() { - let path = entry.unwrap().path(); - let name = path.file_stem().unwrap().to_str().unwrap(); - if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || name.starts_with("pbs-generic-struct-") || name.starts_with("pbs-list-") || name.starts_with("pbs-linked-") || name.starts_with("pbs-hash-") || name.starts_with("pbs-set-") || name.starts_with("pbs-map-") || name.starts_with("pbs-stack-") || name.starts_with("pbs-queue-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; } - count += 1; - let bytes = std::fs::read(&path).unwrap(); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|e| panic!("{name}: {e:?}")); - for (index, ty) in image.registry().declarations().types.iter().enumerate() { - if let prometeu_bytecode::registry::TypeKind::Builtin(id) = ty.kind { - let expected = match id.0 { - 1 | 0x11 => vec![Value::Int64(0)], - 2 => vec![Value::Float(0.0), Value::Float(0.0)], - 3 => vec![Value::Int64(0), Value::Int64(0), Value::Int64(0)], - 0x10 => vec![Value::Int32(0)], 0x12 => vec![Value::Float(0.0)], - 0x13 => vec![Value::Boolean(false)], 0x14 => vec![Value::Null], - _ => panic!("unexpected PBS builtin {}", id.0), - }; - assert_eq!(image.registry().type_layout(prometeu_bytecode::registry::TypeId(index as u32)).unwrap().storage.default_values(), expected); - defaults_checked.insert(id.0); - } - } - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let parts: Vec<_> = name.split('-').collect(); - if parts[1] == "pad" || parts[1] == "touch" { - let query = if parts[1] == "pad" { &parts[3] } else { parts.last().unwrap() }; - let expected = if parts[1] == "pad" { buttons.iter().position(|b| *b == parts[2]).unwrap() } - else { match *query { "x" => 13, "y" => 14, _ => 12 } }; - let button = prometeu_hal::button::Button { pressed: expected % 2 == 0, released: expected % 3 == 0, down: expected % 5 == 0, hold_frames: 100 + expected as u16 }; - let value = match *query { - "pressed" => Value::Boolean(button.pressed), "released" => Value::Boolean(button.released), "down" => Value::Boolean(button.down), - "hold" => Value::Int64(button.hold_frames.into()), "x" => Value::Int64(-123), "y" => Value::Int64(456), _ => unreachable!() - }; - let mut input = PbsInput { expected, reads: std::cell::Cell::new(0), button }; - let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(Some(&mut input))).unwrap(); - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - assert_eq!(vm.operand_stack_top(1), vec![value], "{name}"); - assert_eq!(input.reads.get(), 1, "{name}: exactly one input query"); - let unavailable_image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut unavailable_vm = VirtualMachine::from_image(unavailable_image, Default::default()); - unavailable_vm.prepare_boot_call().unwrap(); - let unavailable = unavailable_vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(unavailable.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_UNAVAILABLE)); - } else { - let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - match parts[1] { - "numeric" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{report:?}"); assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(2147483655)]); } - "vec2" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(2), vec![Value::Float(0.0),Value::Float(0.0)]); } - "tuple" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(2), vec![Value::Int64(8),Value::Int32(7)]); } - "named" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(211020)]); } - "color" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(0xFF0000FF)]); } - "pixel" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{report:?}"); assert_eq!(vm.operand_stack_top(3), vec![Value::Int64(0xFF0000FF),Value::Int64(-34),Value::Int64(12)]); } - "string" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert!(matches!(&vm.operand_stack_top(1)[0], Value::String(value) if value.as_ref() == "hello")); } - "division" => assert!(matches!(report.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_DIV_ZERO)), - "minimum" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(i64::MIN)]); } - "float" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{report:?}"); assert_eq!(vm.operand_stack_top(1), vec![Value::Float(3.75)]); } - "overflow" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(i32::MIN)]); } - "narrow" => assert!(matches!(report.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_NUMERIC_RANGE), "{name}: {report:?}"), - _ => panic!("unasserted PBS fixture: {name}"), - } - } - println!("PBS SOURCE/LOAD/EXEC PASS {name}"); - } - assert_eq!(defaults_checked, [1,2,3,0x10,0x11,0x12,0x13,0x14].into_iter().collect()); - println!("PBS Registry defaults PASS: all eight existing value types"); - assert_eq!(count, 114, "The complete PBS qualification corpus must be present"); -} - -fn verify_pbs_structured_fixtures(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - let success = ["closure-import", "closure-installed", "closure-groups", "closure-isolation", "closure-fields", "closure-functions", "closure-snapshot", "closure-objects", "closure-nested", "array-cycle", "array-nested", "array-parametric", "optional-flow", "struct-contract", "service-contract", - "optional-tuple", "tuple-storage", "optional-intrinsics", "optional-lazy", "array-context", - "binding-scope", "overloads", "single-evaluation", "long-boundaries", "gc-roots", "native-groups", "contract-elements", "imports", "global-array", "installed-example", "return-overloads", "inferred-optional-tuple", "inline-integers"]; - for name in success.into_iter().chain(["negative-index", "past-end", "negative-length", "large-length"]) { - let bytes = std::fs::read(root.join(format!("pbs-structured-{name}.pbx"))) - .unwrap_or_else(|e| panic!("missing mandatory PBS structured fixture {name}: {e}")); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|e| panic!("{name}: {e:?}")); - let limits = if name == "inline-integers" { - prometeu_vm::resource_budget::RuntimeLimits::default() - .lowered(prometeu_vm::resource_budget::RuntimeResource::HandleSlots, 1).unwrap() - } else { Default::default() }; - let mut vm = VirtualMachine::from_image(image, limits); - vm.prepare_boot_call().unwrap(); - let mut report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - if name == "gc-roots" { - assert!(matches!(report.reason, End::FrameSync), "{report:?}"); - let snapshot = vm.resource_snapshot(); - assert_eq!(snapshot.gc.collections, 1); - assert!(snapshot.gc.reclaimed >= 1100, "{:?}", snapshot.gc); - report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - } - match name { - "negative-index" | "past-end" | "negative-length" => assert!(matches!(report.reason, - End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_OOB), "{name}: {report:?}"), - "large-length" => assert!(matches!(report.reason, - End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}: {report:?}"), - _ => { - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}"); - } - } - if name == "inline-integers" { assert_eq!(vm.heap().len(), 1, "single-slot integers must not allocate boxes"); } - let ownership = vm.resource_observer(); - drop(vm); - for resource in [prometeu_vm::resource_budget::RuntimeResource::StringBytes, - prometeu_vm::resource_budget::RuntimeResource::StringAllocations] { - assert_eq!(ownership.used(resource), 0, "{name}: string ownership released"); - } - println!("PBS STRUCTURED SOURCE/LOAD/EXEC PASS {name}"); - } -} - -fn verify_pbs_generic_struct_fixtures(root: &std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}}; - use prometeu_bytecode::registry::TypeKind; - let mut object_heap = None; - let mut function_heap = None; - for name in ["basic", "manual", "constructor", "phantom", "tuple", "optional", "array", "recursive", - "combined", "function", "function-manual", "gc", "imports", "installed", "multiple", "origins"] { - let bytes = std::fs::read(root.join(format!("pbs-generic-struct-{name}.pbx"))) - .unwrap_or_else(|error| panic!("missing mandatory generic struct/function fixture {name}: {error}")); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|error| panic!("generic struct/function {name}: {error:?}")); - let declarations = image.registry().declarations(); - if name == "phantom" { - let structs = declarations.types.iter().filter(|t| matches!(t.kind, TypeKind::Struct(_)) - && t.name.as_deref().is_some_and(|name| name.starts_with("Marker<"))).count(); - assert_eq!(structs, 2, "phantom arguments preserve distinct nominal applications"); - } - if name == "origins" { - assert_eq!(declarations.types.iter().filter(|t| t.name.as_deref() == Some("Enemy")).count(), 2); - assert_eq!(declarations.types.iter().filter(|t| t.name.as_deref() == Some("Box")).count(), 2); - } - if name == "combined" || name == "imports" { - assert_eq!(declarations.implementations.len(), 1, "one concrete owner/contract pair, shared across aliases"); - let first = &declarations.implementations[0]; - assert_eq!(image.registry().implementation(first.owner, first.trait_id).unwrap().0, 0); - } - println!("PBS GENERIC STRUCT METADATA {name}: types={} implementations={} bytes={}", declarations.types.len(), declarations.implementations.len(), bytes.len()); - let limits = if ["basic", "manual", "function", "function-manual"].contains(&name) { - RuntimeLimits::default().lowered(RuntimeResource::HandleSlots, 1).unwrap() - } else { RuntimeLimits::default() }; - let mut vm = VirtualMachine::from_image(image, limits); - let observer = vm.resource_observer(); - vm.prepare_boot_call().unwrap(); - let mut report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - if name == "gc" { - assert!(matches!(report.reason, End::FrameSync), "{name}: {report:?}"); - let gc = vm.resource_snapshot().gc; - assert!(gc.collections >= 1 && gc.reclaimed >= 1100, "{gc:?}"); - report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - } - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - if name != "imports" && name != "origins" { assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}"); } - if name == "basic" || name == "manual" { - assert_eq!(vm.heap().len(), 1, "one object, without a generic wrapper"); - let heap = observer.used(RuntimeResource::GuestBytes); - if let Some(reference) = object_heap { assert_eq!(heap, reference); } - object_heap = Some(heap); - } - if name == "function" || name == "function-manual" { - let heap = observer.used(RuntimeResource::GuestBytes); - if let Some(reference) = function_heap { assert_eq!(heap, reference); } - function_heap = Some(heap); - } - drop(vm); - for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, - RuntimeResource::TemporaryBytes, RuntimeResource::StringBytes, RuntimeResource::StringAllocations] { - assert_eq!(observer.used(resource), 0, "{name}: release {resource:?}"); - } - if name == "basic" || name == "combined" { - for (resource, limit) in [(RuntimeResource::GuestBytes, 0), (RuntimeResource::HandleSlots, 0)] { - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut refused = VirtualMachine::from_image(image, RuntimeLimits::default().lowered(resource, limit).unwrap()); - let observed = refused.resource_observer(); - refused.prepare_boot_call().unwrap(); - let report = refused.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}/{resource:?}: {report:?}"); - assert_eq!(refused.heap().len(), 0); - assert!(observed.used(resource) <= limit); - drop(refused); - for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] { - assert_eq!(observed.used(domain), 0); - } - } - } - println!("PBS GENERIC STRUCT SOURCE/LOAD/EXEC PASS {name}"); - } -} - -fn verify_pbs_generic_contract_fixtures(root: &std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}}; - use prometeu_bytecode::{registry::{TypeId, TypeKind}, isa::core::CoreOpCode}; - let mut reference_heap = None; - for name in ["identity", "manual", "multiple", "tuple", "optional", "function", "contract", "native", "recursive", "phantom", "receiver", "gc", "installed", "imports"] { - let bytes = std::fs::read(root.join(format!("pbs-generic-contract-{name}.pbx"))) - .unwrap_or_else(|error| panic!("missing mandatory generic-contract fixture {name}: {error}")); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|error| panic!("generic contract {name}: {error:?}")); - let declarations = image.registry().declarations(); - let traits: Vec<_> = declarations.types.iter().enumerate().filter(|(_, t)| matches!(t.kind, TypeKind::Trait(_))).collect(); - assert!(!traits.is_empty(), "{name}: source must emit concrete traits"); - for (index, _) in &traits { - assert_eq!(image.registry().type_layout(TypeId(*index as u32)).unwrap().storage.default_values(), &[Value::Null, Value::Null], "{name}: absent concrete trait"); - } - assert!(!declarations.implementations.is_empty()); - // The first dense implementation is valid; zero must never act as an absence sentinel. - assert_eq!(image.registry().implementation(declarations.implementations[0].owner, declarations.implementations[0].trait_id).unwrap().0, 0); - if name == "multiple" || name == "phantom" { - assert_eq!(traits.len(), 2); - assert_eq!(declarations.implementations.len(), 2); - assert_eq!(declarations.implementations[0].owner, declarations.implementations[1].owner); - assert_ne!(declarations.implementations[0].trait_id, declarations.implementations[1].trait_id); - } - if name == "imports" { assert_eq!(traits.len(), 3); assert_eq!(declarations.implementations.len(), 3); } - if name == "phantom" { - let mut code = image.code().to_vec(); - let mut pc = 0; - let mut changed = false; - while pc < code.len() { - let instruction = prometeu_bytecode::decode_next(pc, &code).unwrap(); - if instruction.opcode == CoreOpCode::CallTrait { - let (original, _) = instruction.imm_u32x2().unwrap(); - let other = traits.iter().map(|(index, _)| *index as u32).find(|id| *id != original).unwrap(); - code[pc+2..pc+6].copy_from_slice(&other.to_le_bytes()); - changed = true; break; - } - pc = instruction.next_pc; - } - assert!(changed); - let corrupt = replace(&bytes, 2, &code); - match ValidatedProgramImage::load(&corrupt, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) { - Err(error) => record_fault(root, "generic-contract-wrong-view", error), - Ok(image) => { - // Unknown receiver facts may defer rejection to the mandatory runtime check. - let mut invalid = VirtualMachine::from_image(image, RuntimeLimits::default()); - invalid.prepare_boot_call().unwrap(); - let report = invalid.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_TYPE), "mismatched concrete view: {report:?}"); - } - } - println!("PBS GENERIC WRONG-VIEW REJECTION PASS"); - } - println!("PBS GENERIC METADATA {name}: types={} implementations={} bytes={}", declarations.types.len(), declarations.implementations.len(), bytes.len()); - let limits = if name == "identity" || name == "manual" { - RuntimeLimits::default().lowered(RuntimeResource::HandleSlots, 1).unwrap() - } else { RuntimeLimits::default() }; - let mut vm = VirtualMachine::from_image(image, limits); - let observer = vm.resource_observer(); - vm.prepare_boot_call().unwrap(); - let mut report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - if name == "gc" { - assert!(matches!(report.reason, End::FrameSync), "{name}: {report:?}"); - let gc = vm.resource_snapshot().gc; - assert!(gc.collections >= 1 && gc.reclaimed >= 1100, "{gc:?}"); - report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - } - if name == "imports" { - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - } else { - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}"); - } - if name == "identity" || name == "manual" { - assert_eq!(vm.heap().len(), 1, "no generic argument box or view wrapper"); - let heap = observer.used(RuntimeResource::GuestBytes); - if let Some(reference) = reference_heap { assert_eq!(heap, reference, "generic and manual contract heap footprints"); } - reference_heap = Some(heap); - } - drop(vm); - for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, - RuntimeResource::TemporaryBytes, RuntimeResource::StringBytes, RuntimeResource::StringAllocations] { - assert_eq!(observer.used(resource), 0, "{name}: release {resource:?}"); - } - if name == "identity" || name == "receiver" { - for (resource, limit) in [(RuntimeResource::GuestBytes, 0), (RuntimeResource::GuestBytes, 1), (RuntimeResource::GuestBytes, 2), (RuntimeResource::HandleSlots, 0)] { - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut refused = VirtualMachine::from_image(image, RuntimeLimits::default().lowered(resource, limit).unwrap()); - let observed = refused.resource_observer(); - refused.prepare_boot_call().unwrap(); - let report = refused.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}/{resource:?}: {report:?}"); - assert_eq!(refused.heap().len(), 0, "refusal cannot publish partial objects"); - assert!(observed.used(resource) <= limit); - drop(refused); - for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] { - assert_eq!(observed.used(domain), 0); - } - } - reject(root, &format!("generic-contract-{name}-load-quota"), &bytes, LoadLimits { implementations: 0, ..LoadLimits::default() }); - } - println!("PBS GENERIC SOURCE/LOAD/EXEC PASS {name}"); - } -} - -fn verify_pbs_resource_refusals(root: &std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}}; - for name in ["closure-objects", "array-cycle", "tuple-storage", "struct-contract"] { - for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots] { - for limit in [0, 1, 2] { - let bytes = std::fs::read(root.join(format!("pbs-structured-{name}.pbx"))).unwrap(); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let limits = RuntimeLimits::default().lowered(resource, limit).unwrap(); - let mut vm = VirtualMachine::from_image(image, limits); - let observer = vm.resource_observer(); - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}/{resource:?}/{limit}: {report:?}"); - assert!(observer.used(resource) <= limit); - if limit == 0 { assert_eq!(vm.heap().len(), 0, "no partially published object"); } - drop(vm); - for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, - RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] { - assert_eq!(observer.used(domain), 0, "{name}: session ownership released after refusal: {domain:?}"); - } - println!("PBS QUOTA/OWNERSHIP PASS {name}/{resource:?}/{limit}"); - } - } - } -} - -fn verify_pbs_closure_frames(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - let bytes = std::fs::read(root.join("closure-frame-lifecycle.pbx")).expect("mandatory closure frame fixture"); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut vm = VirtualMachine::from_image(image, Default::default()); - for frame in 0..3 { - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(2_000_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "frame {frame}: {report:?}"); - assert!(vm.operand_stack_top(1).is_empty(), "frame root returns void"); - let snapshot = vm.resource_snapshot(); - assert!(snapshot.gc.collections >= frame + 1, "frame {frame}: {:?}", snapshot.gc); - assert!(snapshot.gc.reclaimed >= (frame + 1) * 1200, "frame {frame}: {:?}", snapshot.gc); - if frame == 0 { assert!(vm.heap().len() >= 3, "array, closure and capture survive root return"); } - else { assert_eq!(vm.heap().len(), 1, "only the empty global array remains after closure release"); } - } - println!("PBS CLOSURE FRAME LIFECYCLE/RETENTION/GC PASS"); -} - -// The expected results/call costs are independent provider fixtures. Step costs -// use the published opcode contract, not observed timings or compiler estimates. -fn verify_pbs_math_fixtures(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - use prometeu_bytecode::isa::core::CoreOpCode as OpCode; - let corpus = std::fs::read_to_string(root.join("math-vectors.tsv")).expect("mandatory math corpus"); - let mut covered = std::collections::BTreeSet::new(); - let mut count = 0; - let mut original_cycles = std::collections::BTreeMap::new(); - let mut names = std::collections::BTreeSet::new(); - for line in corpus.lines() { - let parts: Vec<_> = line.split_whitespace().collect(); - let name = parts[0]; - assert!(names.insert(parts[0]), "duplicate math fixture"); - let id = u32::from_str_radix(parts[1], 16).unwrap(); - let expected = parts[parts.len()-2]; - let cost: u64 = parts.last().unwrap().parse().unwrap(); - let bytes = std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let code = image.code().to_vec(); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let mut total = 0; - let mut calls = 0; - let ending = loop { - let pc = vm.pc(); - let opcode = OpCode::try_from(u16::from_le_bytes(code[pc..pc+2].try_into().unwrap())).unwrap(); - let cycles = if opcode == OpCode::Intrinsic { - let actual = u32::from_le_bytes(code[pc+2..pc+6].try_into().unwrap()); - assert_eq!(actual, id, "{name}: wrong overload or unexpected conversion"); - calls += 1; - cost - } else { opcode.cycles() }; - let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert_eq!(report.cycles_used, cycles, "{name}: cycle charge at {pc}, {opcode:?}"); - total += cycles; - if matches!(report.reason, End::Halted | End::EndOfRom | End::Trap(_)) { break report.reason; } - assert!(total < 10000, "{name}: nonterminating source fixture"); - }; - assert_eq!(calls, 1, "{name}: preserve literal calls and no hidden conversions"); - if let Some(code) = expected.strip_prefix("trap:") { - let code = u32::from_str_radix(code,16).unwrap(); - assert!(matches!(ending, End::Trap(ref trap) if trap.code == code), "{name}: {ending:?}"); - } else { - assert!(matches!(ending, End::Halted | End::EndOfRom), "{name}: {ending:?}"); - let value = vm.operand_stack_top(1); - let actual = match &value[0] { - Value::Float(value) => format!("f:{:016x}",value.to_bits()), - Value::Int32(value) => format!("i:{value}"), - Value::Int64(value) => format!("l:{value}"), - value => panic!("{name}: unexpected value {value:?}"), - }; - assert_eq!(actual, expected, "{name}: exact result bits"); - } - // A full-budget execution must charge exactly the independently checked steps. - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert_eq!(report.cycles_used, total, "{name}: aggregate cost"); - if let Some(original) = name.strip_suffix("-optimized") { - assert_eq!(original_cycles.get(original), Some(&total), "{name}: optimization changed cycles"); - } else { original_cycles.insert(name.to_string(), total); } - covered.insert(id); - count += 1; - } - assert_eq!(covered, (0x3000..=0x3019).collect()); - assert_eq!(count, 522, "mandatory boundary corpus missing"); - for (name, expected) in [("pi", Value::Float(f64::from_bits(0x400921fb54442d18))), - ("tau", Value::Float(f64::from_bits(0x401921fb54442d18))), - ("literal", Value::Float(-0.0)), ("dependency", Value::Int32(42)), ("long", Value::Int64(2147483648)), - ("service", Value::Int32(42)), ("min", Value::Int64(42))] { - let bytes = std::fs::read(root.join(format!("pbs-math-{name}.pbx"))).unwrap(); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); - let actual = vm.operand_stack_top(1); - match (&actual[0], &expected) { - (Value::Float(a), Value::Float(b)) => assert_eq!(a.to_bits(), b.to_bits(), "{name}"), - _ => assert_eq!(actual, vec![expected]), - } - if name == "pi" || name == "tau" || name == "service" { assert_eq!(report.cycles_used, 6, "constant load + root RET only"); } - } - let bytes = std::fs::read(root.join("pbs-math-import.pbx")).expect("real SDK imports fixture"); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason, End::Halted | End::EndOfRom), "import: {report:?}"); - println!("PBS MATH PASS: {count} exact bits/faults/cycle vectors; all 26 signatures; service constants"); -} - - -fn verify_pbs_random_fixtures(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - use prometeu_bytecode::isa::core::CoreOpCode as OpCode; - let corpus = std::fs::read_to_string(root.join("random-vectors.tsv")).expect("mandatory random seed corpus"); - let mut cases: Vec<(String, Vec, Vec, Option)> = Vec::new(); - let mut names = std::collections::BTreeSet::new(); - for row in corpus.lines() { - let p: Vec<_> = row.split_whitespace().collect(); - assert!(names.insert(p[0]), "duplicate random fixture"); - let draw: usize = p[2].parse().unwrap(); - assert!((1..=8).contains(&draw)); - let mut costs = vec![32]; - costs.extend(std::iter::repeat_n(8, draw-1)); - costs.push(if p[1].starts_with("f:") { 12 } else { 8 }); - cases.push((p[0].to_string(), vec![p[1].to_string()], costs, None)); - } - assert_eq!(cases.len(), 192, "six seeds, eight draws, two outputs, two optimizer variants required"); - let words = [0x86B1DA1D72062B68u64, 0x1304AA46C9853D39, 0xA3670E9E0DD50358, 0xF9090E529A7DAE00]; - let long = |word: u64| format!("l:{}",word as i64); - let mut add = |name: &str, expected: Vec, costs: Vec, fault: Option| { - for suffix in ["", "-optimized"] { - cases.push((format!("pbs-random-{name}{suffix}"), expected.clone(), costs.clone(), fault)); - } - }; - add("mixed", vec![long(words[3]), "l:-7".into(), "f:3fb304aa46c98538".into()], vec![32,8,12,12,8], None); - add("storage", vec![long(words[0]),long(words[3]),long(words[2]),long(words[1]),long(words[0])], vec![32,32,8,8,8,8,32,8], None); - for (name, trace) in [("named",312),("positional",123)] { - add(name,vec![long(words[3]),"l:-7".into(),format!("i:{trace}")],vec![32,32,8,8,12,8],None); - } - let bounds = [(0,1),(-10,-3),(-10,10),(0,16),(i64::MIN,0),(-1,i64::MAX),(i64::MIN,i64::MAX)]; - for (index,(min,max)) in bounds.into_iter().enumerate() { - let span = (i128::from(max)-i128::from(min)) as u64; - // Independent provider fixture word, accepted for each of these spans. - let expected = i128::from(min)+i128::from(words[0]%span); - assert!(expected>=i128::from(min) && expected=1100,"{name}: {:?}",snapshot.gc); - } - assert!(total<1000000,"{name}: nontermination"); - }; - if budget==1 { assert_eq!(calls,costs.len(),"{name}: missing or extra calls"); } - if let Some(fault)=fault { - assert!(matches!(ending,End::Trap(ref t) if t.code==fault),"{name}: {ending:?}"); - } else { - assert!(matches!(ending,End::Halted|End::EndOfRom),"{name}: {ending:?}"); - let actual:Vec<_>=vm.operand_stack_top(expected.len()).iter().map(|v|match v { - Value::Int64(v)=>format!("l:{v}"),Value::Int32(v)=>format!("i:{v}"), - Value::Float(v)=>format!("f:{:016x}",v.to_bits()),v=>panic!("{name}: {v:?}") - }).collect(); - assert_eq!(actual,expected,"{name}: output bits/replay"); - } - if let Some(reference)=reference { assert_eq!(total,reference,"{name}: replay/budget cycles"); } - reference=Some(total); - } - let total=reference.unwrap(); - if let Some(original)=name.strip_suffix("-optimized") { - assert_eq!(cycles_by_name.get(original),Some(&total),"{name}: optimizer cycles"); - } else { cycles_by_name.insert(name.clone(),total); } - println!("RANDOM PASS {name}: {total} cycles, exact bits/fault and replay"); - } - let bytes=std::fs::read(root.join("pbs-random-import.pbx")).expect("mandatory real Random SDK import"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image,Default::default()); - vm.prepare_boot_call().unwrap(); - let report=vm.run_budget(10000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::Halted|End::EndOfRom),"Random import: {report:?}"); - println!("RANDOM PASS real SDK imports and aliases"); - -} - - -fn verify_pbs_list_cursor_fixtures(root: &std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits,RuntimeResource}}; - use prometeu_bytecode::TRAP_EXPLICIT; - let successful=["basic","construction","capacity","holes","structural-growth","cursor-empty","cursor-single", - "cursor-many","snapshot","false-present","shared-optional","identity","tuple","nested-array","function","evaluation","vec2","pixel","contract"]; - let faults=[("fault-read",TRAP_EXPLICIT),("fault-write",TRAP_EXPLICIT),("fault-negative",TRAP_EXPLICIT), - ("fault-insert",TRAP_EXPLICIT),("fault-length",TRAP_EXPLICIT),("fault-overflow",TRAP_EXPLICIT), - ("fault-long-index",TRAP_EXPLICIT),("fault-constructor",TRAP_EXPLICIT)]; - let cases=successful.into_iter().map(|n|(n,None)).chain(faults.into_iter().map(|(n,c)|(n,Some(c)))) - .flat_map(|(name,fault)|[(name.to_string(),fault),(format!("{name}-optimized"),fault)]); - for (name,fault) in cases { - let bytes=std::fs::read(root.join(format!("pbs-list-{name}.pbx"))) - .unwrap_or_else(|e|panic!("missing mandatory SDK List/Cursor fixture {name}: {e}")); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE) - .unwrap_or_else(|e|panic!("List/Cursor {name}: {e:?}")); - let mut vm=VirtualMachine::from_image(image,RuntimeLimits::default()); - let observer=vm.resource_observer(); - vm.prepare_boot_call().unwrap(); - let report=vm.run_budget(1_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if let Some(code)=fault { - let End::Trap(info)=report.reason else {panic!("{name}: {report:?}")}; - assert_eq!(info.code,code,"{name}: {info:?}"); - } else { - assert!(matches!(report.reason,End::Halted|End::EndOfRom),"{name}: {report:?}"); - assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)],"{name}"); - } - drop(vm); - for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots,RuntimeResource::AuxiliaryBytes, - RuntimeResource::TemporaryBytes,RuntimeResource::StringBytes,RuntimeResource::StringAllocations] { - assert_eq!(observer.used(resource),0,"{name}: final owner release {resource:?}"); - } - println!("PBS LIST/CURSOR SOURCE/LOAD/EXEC PASS {name}"); - } - verify_list_cursor_refusals(root); - verify_list_cursor_gc(root); - verify_list_cursor_distribution(root); -} - - -fn list_storage(vm:&VirtualMachine,image:&ValidatedProgramImage)->(prometeu_vm::resource_diagnostics::StorageObject,prometeu_vm::resource_diagnostics::StorageObject) { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let objects=vm.heap().diagnostic_typed_storage(); - let object=objects.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("list")) - .expect("one source List remains observable").clone(); - let V::Reference(backing)=object.groups[0][0] else {panic!("List storage reference")}; - let array=objects.iter().find(|o|o.reference==backing).unwrap().clone(); - (object,array) -} - -// Non-owning diagnostic snapshots observe only objects reachable before the operation. -// Compare every instruction prefix against a successful execution, so a refused -// instruction preserves its own entry state without inventing method rollback. -type ObservedStorage = Vec; -type MutationPrefix = (usize, ObservedStorage); -fn observe_originals(vm:&VirtualMachine, original:&ObservedStorage)->ObservedStorage { - let objects=vm.heap().diagnostic_typed_storage(); - original.iter().filter_map(|old|objects.iter().find(|now|now.reference==old.reference).cloned()).collect() -} -fn trace_collection_attempt(vm:&mut VirtualMachine, original:&ObservedStorage, stop_pc:usize) - ->(prometeu_vm::BudgetReport, Vec, bool) { - use prometeu_vm::LogicalFrameEndingReason as End; - let mut prefixes=Vec::new(); let mut mutated=false; - for _ in 0..200_000 { - let before=observe_originals(vm,original); - mutated|=before!=*original; - prefixes.push((vm.pc(),before.clone())); - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - let after=observe_originals(vm,original); - if matches!(report.reason,End::Trap(_)) { - assert_eq!(after,before,"refused instruction preserves its own observable entry state"); - } - mutated|=after!=*original; - if vm.pc()==stop_pc || !matches!(report.reason,End::BudgetExhausted) {return (report,prefixes,mutated);} - } - panic!("collection operation did not reach its completion marker"); -} -fn assert_mutation_prefix(actual:&[MutationPrefix], successful:&[MutationPrefix]) { - assert!(actual.len()<=successful.len(),"refusal must be a successful instruction prefix"); - for (index,(left,right)) in actual.iter().zip(successful).enumerate() { - assert_eq!(left,right,"observable effects differ at source-operation instruction {index}"); - } -} - -fn verify_list_cursor_refusals(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits,RuntimeResource as Q}}; - use prometeu_vm::resource_diagnostics::StorageValue as V; - use prometeu_bytecode::{decode_next,TRAP_RESOURCE_LIMIT}; - use prometeu_bytecode::isa::core::CoreOpCode as Op; - let mut copy_scratch=false;let mut return_carrier=false;let mut nodes=false;let mut candidate=false;let mut operand_preparation=false; - for name in ["insert","remove","growth","cursor"] { - for suffix in ["","-optimized"] { - println!("PHASE CORPUS list {name}{suffix}"); - let bytes=std::fs::read(root.join(format!("pbs-list-refusal-{name}{suffix}.pbx"))).expect("mandatory refusal fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let marker=|value:i32| { - let mut pc=0;let mut found=Vec::new(); - while pc129,"remove"=>127,_=>128}; - assert_eq!(changed.0.groups[1],[V::Int64(expected_size)],"{name} logical size after success"); - if name=="remove" {assert_eq!(changed.1.groups[12][1],V::Int32(13));assert_eq!(changed.1.groups[127],[V::Null,V::Null]);} - if name=="insert" {assert_eq!(changed.1.groups[12][1],V::Int32(42));assert_eq!(changed.1.groups[13][1],V::Int32(12));} - if name=="growth" {assert_eq!(changed.1.groups.len(),192);assert_eq!(changed.1.groups[128][1],V::Int32(42));} - if name=="cursor" {assert_eq!(changed,original);} - let mut refusals=0; - for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes] { - let lower=before.budget.peaks[q as usize];let upper=completed.budget.peaks[q as usize]; - if lower>=upper {continue;} - let mut limits=vec![lower,lower+(upper-lower)/4,lower+(upper-lower)/2,upper-1]; - if q==Q::HandleSlots {limits.extend(lower..upper.min(lower+16));} - limits.sort_unstable();limits.dedup(); - for limit in limits { - let mut vm=prepare(RuntimeLimits::default().lowered(q,limit).unwrap()); - let observer=vm.resource_observer(); - let setup=vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(setup.reason,End::Breakpoint),"{name} setup at {q:?}={limit}: {setup:?}"); - let state=list_storage(&vm,&image); - vm.remove_breakpoint(before_pc); - let watched=vec![state.0.clone(),state.1.clone()]; - let (report,prefix,mutated)=trace_collection_attempt(&mut vm,&watched,after_pc); - assert_mutation_prefix(&prefix,&successful_prefix); - if let End::Trap(info)=report.reason { - assert_eq!(info.code,TRAP_RESOURCE_LIMIT,"{name} at {q:?}={limit}: {info:?}"); - if !mutated || name=="cursor" { - assert_eq!(list_storage(&vm,&image),state,"{name}: failure before mutation preserves slots/backing/size"); - } - let instruction=decode_next(info.pc as usize,image.code()).unwrap(); - copy_scratch|=q==Q::TemporaryBytes&&instruction.opcode==Op::ArrayCopy; - operand_preparation|=q==Q::AuxiliaryBytes; - candidate|=name=="growth"&&instruction.opcode==Op::ArrayNew; - if instruction.opcode==Op::StructNew { - let ty=instruction.imm_u32().unwrap(); - let declaration=&image.registry().declarations().types[ty as usize]; - nodes|=name=="cursor"&&declaration.name.as_deref().is_some_and(|n|n.starts_with("_SnapshotNode<")); - if name=="remove" { - if let prometeu_bytecode::registry::TypeKind::Struct(fields)=&declaration.kind { - return_carrier|=fields.len()==1&&matches!(image.registry().declarations().types[fields[0].type_id.0 as usize].kind, - prometeu_bytecode::registry::TypeKind::Builtin(prometeu_bytecode::registry::BuiltinId::INT32)); - } - } - } - refusals+=1; - println!("PBS LIST PHASE REFUSAL {name} mutated={mutated} resource={q:?} limit={limit} opcode={:?}",instruction.opcode); - } else {assert!(matches!(report.reason,End::BudgetExhausted|End::Breakpoint) && vm.pc()==after_pc,"{name}: {report:?}");} - drop(vm); - for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes] {assert_eq!(observer.used(resource),0);} - } - } - assert!(refusals>0,"{name}: mandatory source refusals executed"); - } - } - assert!(copy_scratch,"no-growth copy scratch refusal"); - assert!(return_carrier,"removeAt optional return allocation refusal"); - assert!(candidate,"growth candidate allocation refusal"); - assert!(nodes,"snapshot node allocation refusal"); - assert!(operand_preparation,"source operation operand/frame preparation refusal"); -} - -fn verify_list_cursor_gc(root:&std::path::Path) { verify_collection_cursor_gc(root,"list"); } - -fn verify_collection_cursor_gc(root:&std::path::Path,collection:&str) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeLimits}; - use prometeu_vm::resource_diagnostics::StorageValue as V; - let bytes=std::fs::read(root.join(format!("pbs-{collection}-gc.pbx"))).expect("mandatory snapshot GC fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),RuntimeLimits::default());vm.prepare_boot_call().unwrap(); - let mut previous=0; - for (round,(nodes,items)) in [(1200,1200),(1,1),(1,1),(0,0)].into_iter().enumerate() { - let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::FrameSync),"snapshot GC {round}: {report:?}"); - let snapshot=vm.resource_snapshot();assert!(snapshot.gc.collections>previous);previous=snapshot.gc.collections; - let objects=vm.heap().diagnostic_typed_storage(); - assert!(!objects.iter().any(|o|matches!(image.registry().declarations().types[o.type_id.0 as usize].kind, - prometeu_bytecode::registry::TypeKind::Array(_))),"Cursor retains no source or snapshot array"); - let named=|name:&str|objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).collect::>(); - assert_eq!(named("_SnapshotNode").len(),nodes,"prefix nodes round {round}"); - if collection=="linked" {assert!(named("_LinkedNode").is_empty(),"snapshot does not retain original Linked nodes");} - if collection=="set" {assert!(named("_SetNode").is_empty(),"snapshot does not retain original Set nodes");} - let values=named("Item");assert_eq!(values.len(),items,"captured object roots round {round}"); - if items==1 && collection!="set" {assert_eq!(values[0].groups[0],[V::Int32(1199)],"sticky last payload remains live");} - println!("PBS {} CURSOR GC PASS round={round} nodes={nodes} items={items} collected={}",collection.to_uppercase(),snapshot.gc.reclaimed); - } - let report=vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)]); -} - -fn verify_copy_attempts(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q}}; - use prometeu_bytecode::{decode_next,isa::core::CoreOpCode as Op,TRAP_OOB,TRAP_NULL_REFERENCE,TRAP_RESOURCE_LIMIT}; - for base in ["scalar","vec2","string","zero","bad-range","bad-empty-range","null-source","null-zero","negative-count","huge-count","fault-order"] { - for optimized in [false,true] { - let name=format!("common-copy-{base}{}",if optimized{"-optimized"}else{""}); - let bytes=std::fs::read(root.join(format!("{name}.pbx"))).expect("mandatory copy oracle"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut pc=0;let mut copies=Vec::new(); - while pc")).collect::>(); - assert!(!cursors.is_empty(),"distributed frame actually created its shared snapshot Cursor"); - let mut retained=Vec::new(); - for cursor in cursors { - let V::Reference(current)=cursor.groups[0][0] else {panic!("nonempty Cursor retains its current node carrier")}; - let carrier=objects.iter().find(|o|o.reference==current).unwrap(); - let V::Reference(node)=carrier.groups[0][0] else {panic!("current points at a snapshot node")}; - let node=objects.iter().find(|o|o.reference==node).unwrap(); - let V::Int32(value)=node.groups[0][0] else {panic!("typed captured value")}; - retained.push(value); - assert_eq!(node.groups[1],[V::Null],"{name}: final node has no successor"); - } - retained.sort_unstable(); - let expected=if collection=="linked"&&name=="installed" {vec![20,22]} else {vec![last]}; - if collection=="set" { - assert_eq!(retained.len(),1);assert!([20,22].contains(&retained[0]),"Set has no order guarantee"); - }else{assert_eq!(retained,expected,"{collection} {name}: complete traversal retains each final value");} - println!("PBS {} DISTRIBUTION LOAD/EXEC PASS {name}",collection.to_uppercase()); - } -} - -fn verify_pbs_linked_fixtures(root: &std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits,RuntimeResource}}; - use prometeu_bytecode::TRAP_EXPLICIT; - let successful=["basic","links","construction","long-size","empty-cursor","empty-reverseCursor", - "single-cursor","single-reverseCursor","snapshot","false-present","optional-field","identity","tuple","nested-array","function","evaluation","vec2","pixel","contract"]; - let faults=[("fault-read",TRAP_EXPLICIT),("fault-write",TRAP_EXPLICIT),("fault-negative",TRAP_EXPLICIT), - ("fault-insert",TRAP_EXPLICIT),("fault-remove",TRAP_EXPLICIT),("fault-overflow",TRAP_EXPLICIT),("fault-long-index",TRAP_EXPLICIT)]; - let cases=successful.into_iter().map(|n|(n,None)).chain(faults.into_iter().map(|(n,c)|(n,Some(c)))) - .flat_map(|(name,fault)|[(name.to_string(),fault),(format!("{name}-optimized"),fault)]); - for (name,fault) in cases { - let bytes=std::fs::read(root.join(format!("pbs-linked-{name}.pbx"))) - .unwrap_or_else(|e|panic!("missing mandatory SDK Linked fixture {name}: {e}")); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE) - .unwrap_or_else(|e|panic!("Linked {name}: {e:?}")); - let mut vm=VirtualMachine::from_image(image,RuntimeLimits::default()); - let observer=vm.resource_observer(); - vm.prepare_boot_call().unwrap(); - let report=vm.run_budget(1_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if let Some(code)=fault { - let End::Trap(info)=report.reason else {panic!("{name}: {report:?}")}; - assert_eq!(info.code,code,"{name}: {info:?}"); - } else { - assert!(matches!(report.reason,End::Halted|End::EndOfRom),"{name}: {report:?}"); - assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)],"{name}"); - } - drop(vm); - for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots,RuntimeResource::AuxiliaryBytes, - RuntimeResource::TemporaryBytes,RuntimeResource::StringBytes,RuntimeResource::StringAllocations] { - assert_eq!(observer.used(resource),0,"{name}: final owner release {resource:?}"); - } - println!("PBS LINKED SOURCE/LOAD/EXEC PASS {name}"); - } - verify_linked_collection_gc(root); - verify_linked_refusals(root); - verify_collection_cursor_gc(root,"linked"); - verify_collection_distribution(root,"linked",20); -} - -fn linked_state(vm:&VirtualMachine,image:&ValidatedProgramImage)->Vec { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let objects=vm.heap().diagnostic_typed_storage(); - let root=objects.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("linked")) - .expect("source Linked remains observable"); - let mut pending=vec![root.reference];let mut state=Vec::new(); - while let Some(reference)=pending.pop() { - if state.iter().any(|o:&prometeu_vm::resource_diagnostics::StorageObject|o.reference==reference) {continue;} - let object=objects.iter().find(|o|o.reference==reference).expect("live complete Linked group"); - for group in &object.groups {for value in group {if let V::Reference(r)=value {pending.push(*r);}}} - state.push(object.clone()); - } - state.sort_by_key(|o|(o.reference.index,o.reference.generation));state -} - -fn verify_linked_refusals(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q}}; - use prometeu_vm::resource_diagnostics::StorageValue as V; - use prometeu_bytecode::{decode_next,TRAP_RESOURCE_LIMIT}; - use prometeu_bytecode::isa::core::CoreOpCode as Op; - let mut node_allocation=false;let mut optional_return=false;let mut snapshot_allocation=false;let mut preparation=false; - for name in ["insert","add","addFirst","remove","removeFirst","removeLast","replace","clear","cursor","reverseCursor"] { - for suffix in ["","-optimized"] { - println!("PHASE CORPUS linked {name}{suffix}"); - let bytes=std::fs::read(root.join(format!("pbs-linked-refusal-{name}{suffix}.pbx"))).expect("mandatory Linked refusal fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let marker=|value:i32| { - let mut pc=0;let mut found=Vec::new(); - while pc")).unwrap(); - let expected=match name {"insert"|"add"|"addFirst"=>33,"remove"|"removeFirst"|"removeLast"=>31,"clear"=>0,_=>32}; - assert_eq!(owner.groups[2],[V::Int64(expected)]); - if name=="cursor"||name=="reverseCursor" {assert_eq!(changed,original);} - let mut refused=0; - for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes] { - let lower=before.budget.peaks[q as usize];let upper=after.budget.peaks[q as usize];if lower>=upper {continue;} - let mut limits=vec![lower,lower+(upper-lower)/4,lower+(upper-lower)/2,upper-1]; - if q==Q::HandleSlots {limits.extend(lower..upper.min(lower+24));}limits.sort_unstable();limits.dedup(); - for limit in limits { - let mut vm=prepare(RuntimeLimits::default().lowered(q,limit).unwrap());let observer=vm.resource_observer(); - let setup=vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(setup.reason,End::Breakpoint),"{name} setup {q:?}={limit}: {setup:?}"); - let old=linked_state(&vm,&image);vm.remove_breakpoint(before_pc); - let (report,prefix,mutated)=trace_collection_attempt(&mut vm,&old,after_pc); - assert_mutation_prefix(&prefix,&successful_prefix); - if let End::Trap(info)=report.reason { - assert_eq!(info.code,TRAP_RESOURCE_LIMIT,"{name} {q:?}={limit}: {info:?}"); - if !mutated || name=="cursor" || name=="reverseCursor" { - assert_eq!(linked_state(&vm,&image),old,"{name}: failure before mutation preserves original topology"); - } - let instruction=decode_next(info.pc as usize,image.code()).unwrap(); - preparation|=q==Q::AuxiliaryBytes; - if instruction.opcode==Op::StructNew { - let declaration=&image.registry().declarations().types[instruction.imm_u32().unwrap() as usize]; - node_allocation|=declaration.name.as_deref()==Some("_LinkedNode"); - snapshot_allocation|=declaration.name.as_deref()==Some("_SnapshotNode"); - if name.starts_with("remove") { - if let prometeu_bytecode::registry::TypeKind::Struct(fields)=&declaration.kind { - optional_return|=fields.len()==1&&matches!(image.registry().declarations().types[fields[0].type_id.0 as usize].kind, - prometeu_bytecode::registry::TypeKind::Builtin(prometeu_bytecode::registry::BuiltinId::INT32)); - } - } - } - refused+=1;println!("PBS LINKED PHASE REFUSAL {name} mutated={mutated} resource={q:?} limit={limit} opcode={:?}",instruction.opcode); - } else {assert!(matches!(report.reason,End::BudgetExhausted|End::Breakpoint) && vm.pc()==after_pc,"{name}: {report:?}");} - drop(vm);for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes] {assert_eq!(observer.used(resource),0);} - } - } - assert!(refused>0,"{name}: source-operation phase refusals required"); - } - } - assert!(node_allocation,"new Linked node refusal");assert!(optional_return,"optional removed-value refusal"); - assert!(snapshot_allocation,"snapshot node refusal");assert!(preparation,"frame/operand preparation refusal"); -} - - -fn verify_linked_collection_gc(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeLimits}; - let bytes=std::fs::read(root.join("pbs-linked-gc-collection.pbx")).expect("mandatory Linked removal/clear GC fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),RuntimeLimits::default());vm.prepare_boot_call().unwrap(); - let mut previous=0; - for (round,count) in [1200,1197,0,0].into_iter().enumerate() { - let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::FrameSync),"collection GC {round}: {report:?}"); - let collections=vm.resource_snapshot().gc.collections;assert!(collections>previous,"real collection at round {round}");previous=collections; - let objects=vm.heap().diagnostic_typed_storage(); - for name in ["_LinkedNode","Item"] { - let actual=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count(); - assert_eq!(actual,count,"{name} after removal/clear at round {round}"); - } - println!("PBS LINKED COLLECTION GC PASS round={round} nodes={count} items={count}"); - } - let report=vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)]); -} - - -fn verify_identity_hashing_fixtures(root: &std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - use prometeu_bytecode::{isa::core::CoreOpCode as Op,registry::TypeId}; - let corpus=std::fs::read_to_string(root.join("hash-vectors.tsv")).expect("mandatory hashing oracle manifest"); - let mut originals=std::collections::BTreeMap::new();let mut count=0; - for row in corpus.lines() { - let parts:Vec<_>=row.split_whitespace().collect();let name=parts[0]; - let expected=u64::from_str_radix(parts[1],16).unwrap() as i64; - let id:u32=parts[2].parse().unwrap();let cost:u64=parts[3].parse().unwrap(); - let bytes=std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let code=image.code().to_vec();let mut vm=VirtualMachine::from_image(image,Default::default()); - vm.prepare_boot_call().unwrap();let mut total=0;let mut calls=0; - loop { - let pc=vm.pc();let op=Op::try_from(u16::from_le_bytes(code[pc..pc+2].try_into().unwrap())).unwrap(); - let charge=if op==Op::Intrinsic { - assert_eq!(u32::from_le_bytes(code[pc+2..pc+6].try_into().unwrap()),id,"{name}"); - let before=vm.operand_stack_top(1).to_vec();let zero=vm.run_budget(0,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert_eq!((vm.pc(),zero.cycles_used,zero.steps_executed),(pc,0,0)); - assert_eq!(vm.operand_stack_top(1),before);calls+=1;cost - }else{op.cycles()}; - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert_eq!(report.cycles_used,charge,"{name} at {pc}");total+=charge; - if matches!(report.reason,End::EndOfRom|End::Halted){break;} - assert!(matches!(report.reason,End::BudgetExhausted),"{name}: {report:?}"); - assert!(total<100_000); - } - assert_eq!(calls,1,"{name}");assert_eq!(vm.operand_stack_top(1),vec![Value::Int64(expected)],"{name}"); - if let Some(base)=name.strip_suffix("-optimized") {assert_eq!(originals.get(base),Some(&total),"{name}: optimizer charging");} - else{originals.insert(name.to_string(),total);} - println!("HASH ORACLE/COST/FUEL PASS {name} result={expected} cycles={total}");count+=1; - } - assert_eq!(count,60,"all 30 source scalar/String vectors in both optimizer paths"); - for prefix in ["common-identity","pbs-hash-object","pbs-hash-contract","pbs-hash-array","pbs-hash-function","pbs-hash-random","pbs-hash-discard","pbs-hash-discard-reference"] { - for suffix in ["","-optimized"] { - let name=format!("{prefix}{suffix}");let bytes=std::fs::read(root.join(format!("{name}.pbx"))).expect("mandatory identity fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap_or_else(|e|panic!("{name}: {e:?}")); - let code=image.code().to_vec();let registry=image.registry().clone(); - let mut vm=VirtualMachine::from_image(image,Default::default());let observer=vm.resource_observer(); - vm.prepare_boot_call().unwrap();let mut steps=0;let mut queries=0; - loop { - let pc=vm.pc();let op=Op::try_from(u16::from_le_bytes(code[pc..pc+2].try_into().unwrap())).unwrap(); - let width=|at:usize|registry.type_layout(TypeId(u32::from_le_bytes(code[at..at+4].try_into().unwrap()))).unwrap().storage.slots as u64; - let charge=match op {Op::RefIdentityHash=>Some(8+width(pc+2)),Op::RefIdentityEq=>Some(4+width(pc+2)+width(pc+6)),_=>None}; - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if let Some(charge)=charge {queries+=1;assert_eq!(report.cycles_used,charge,"{name}: typed query charge");} - if matches!(report.reason,End::EndOfRom|End::Halted){break;} - assert!(matches!(report.reason,End::BudgetExhausted),"{name}: {report:?}");steps+=1;assert!(steps<100_000); - } - if prefix=="pbs-hash-discard-reference"{assert_eq!(queries,2,"unused reference queries retain charged work");} - let expected=if prefix=="common-identity"{Value::Boolean(true)}else{Value::Int32(42)}; - assert_eq!(vm.operand_stack_top(1),vec![expected],"{name}");drop(vm); - for resource in [prometeu_vm::resource_budget::RuntimeResource::GuestBytes,prometeu_vm::resource_budget::RuntimeResource::HandleSlots,prometeu_vm::resource_budget::RuntimeResource::StringBytes] { - assert_eq!(observer.used(resource),0,"{name}: owner release"); - } - println!("IDENTITY COMPLETE GROUP/ALIAS/COST PASS {name}"); - } - } - verify_identity_negative_fixtures(root); - -} - - -fn verify_pbs_set_fixtures(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeResource as Q}; - let successes=["basic","construction","arithmetic","scalars","objects","collisions","content","tuple", - "cursor-empty","cursor-single","snapshot","callback-reads","references","random","vec2","pixel","evaluation","contract-snapshot","string-snapshot","false-snapshot"]; - let faults=[("fault-callback-1",prometeu_bytecode::TRAP_EXPLICIT),("fault-callback-2",prometeu_bytecode::TRAP_EXPLICIT), - ("fault-callback-3",prometeu_bytecode::TRAP_EXPLICIT),("fault-callback-4",prometeu_bytecode::TRAP_EXPLICIT), - ("fault-callback-5",prometeu_bytecode::TRAP_DIV_ZERO),("fault-overflow",prometeu_bytecode::TRAP_EXPLICIT)]; - for (base,fault) in successes.into_iter().map(|n|(n,None)).chain(faults.into_iter().map(|(n,f)|(n,Some(f)))) { - for suffix in ["","-optimized"] { - let name=format!("{base}{suffix}");let bytes=std::fs::read(root.join(format!("pbs-set-{name}.pbx"))).unwrap_or_else(|e|panic!("mandatory Set {name}: {e}")); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap_or_else(|e|panic!("Set {name}: {e:?}")); - let registry=image.registry().clone();let mut vm=VirtualMachine::from_image(image,Default::default());let observer=vm.resource_observer(); - vm.prepare_boot_call().unwrap();let report=vm.run_budget(10_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if let Some(code)=fault { - let End::Trap(info)=report.reason else{panic!("{name}: {report:?}")};assert_eq!(info.code,code,"{name}: {info:?}"); - if base.starts_with("fault-callback") { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let objects=vm.heap().diagnostic_typed_storage(); - let set=objects.iter().find(|o|registry.declarations().types[o.type_id.0 as usize].name.as_deref()==Some("set")).expect("faulted Set retained"); - assert_eq!(set.groups[0],vec![V::Null],"{name}: unpublished buckets"); - assert_eq!(set.groups[1],vec![V::Int64(0)],"{name}: old size"); - assert_eq!(set.groups[3],vec![V::Boolean(true)],"{name}: guard is not cleaned after fault"); - } - }else { - assert!(matches!(report.reason,End::Halted|End::EndOfRom),"{name}: {report:?}"); - assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)],"{name}"); - } - drop(vm); - for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations] { - assert_eq!(observer.used(resource),0,"{name}: final resource release {resource:?}"); - } - println!("SET SOURCE/LOAD/EXEC/GUARD PASS {name}"); - } - } - verify_set_refusals(root); - verify_set_postpublication_injection(root); - verify_collection_cursor_gc(root,"set"); - verify_set_collection_gc(root); - verify_collection_distribution(root,"set",0); - verify_installed_hash(root); - -} - - -fn set_state(vm:&VirtualMachine,image:&ValidatedProgramImage)->ObservedStorage { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let objects=vm.heap().diagnostic_typed_storage(); - let owner=objects.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("set")).expect("source Set"); - let mut pending=vec![owner.reference];let mut state:ObservedStorage=Vec::new(); - while let Some(reference)=pending.pop() { - if state.iter().any(|o|o.reference==reference){continue;} - let object=objects.iter().find(|o|o.reference==reference).expect("live complete Set group"); - for value in object.groups.iter().flatten(){if let V::Reference(reference)=value{pending.push(*reference);}} - state.push(object.clone()); - } - state.sort_by_key(|o|(o.reference.index,o.reference.generation));state -} -fn set_without_guard(mut state:ObservedStorage,image:&ValidatedProgramImage)->ObservedStorage { - for object in &mut state { - if image.registry().declarations().types[object.type_id.0 as usize].name.as_deref()==Some("set") { - object.groups[3]=vec![prometeu_vm::resource_diagnostics::StorageValue::Boolean(false)]; - } - } - state -} -fn validate_set(vm:&VirtualMachine,image:&ValidatedProgramImage,expected:i64)->usize { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let state=set_state(vm,image); - let owner=state.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("set")).unwrap(); - assert_eq!(owner.groups[1],vec![V::Int64(expected)]);assert_eq!(owner.groups[3],vec![V::Boolean(false)]); - let get=|reference|state.iter().find(|o|o.reference==reference).expect("reachable object"); - let V::Reference(carrier)=owner.groups[0][0] else{assert_eq!(expected,0);return 0;}; - let V::Reference(table)=get(carrier).groups[0][0] else{panic!("bucket carrier")}; - let buckets=get(table);let capacity=buckets.groups.len();let mut nodes=std::collections::HashSet::new(); - for (bucket,group) in buckets.groups.iter().enumerate() { - if *group==vec![V::Null,V::Null]{continue;} - let [V::Int64(tag),V::Reference(first)]=group.as_slice() else{panic!("complete bucket group")}; - assert_eq!(image.registry().declarations().types[*tag as usize].name.as_deref(),Some("_SetNode")); - let mut next=Some(*first); - while let Some(reference)=next { - assert!(nodes.insert(reference),"each node appears once, no cycles");let node=get(reference); - let V::Int64(hash)=node.groups[0][0] else{panic!("cached complete hash")}; - assert_eq!(hash.rem_euclid(capacity as i64) as usize,bucket); - next=match node.groups[2][0]{V::Null=>None,V::Reference(carrier)=>{let V::Reference(value)=get(carrier).groups[0][0] else{panic!("next node carrier")};Some(value)},_=>panic!("next group")}; - } - } - assert_eq!(nodes.len(),expected as usize);capacity -} -fn verify_set_refusals(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q}}; - use prometeu_bytecode::{decode_next,isa::core::CoreOpCode as Op,TRAP_RESOURCE_LIMIT}; - let mut node_refusal=false;let mut snapshot_refusal=false;let mut table_refusal=false;let mut guard_effect=false; - for name in ["growth","add","duplicate","remove","clear","cursor"] { - for suffix in ["","-optimized"] { - let bytes=std::fs::read(root.join(format!("pbs-set-refusal-{name}{suffix}.pbx"))).expect("mandatory Set resource fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let marker=|value:i32|{let mut pc=0;let mut found=Vec::new();while pc")).count()); - max_tables=max_tables.max(objects.iter().filter(|o|matches!(image.registry().declarations().types[o.type_id.0 as usize].kind,prometeu_bytecode::registry::TypeKind::Array(_))).count()); - successful.push((baseline.pc(),observe_originals(&baseline,&old))); - let report=baseline.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if baseline.pc()==after_pc{break;} - assert!(matches!(report.reason,End::BudgetExhausted),"Set {name}: {report:?}");assert!(successful.len()<200_000); - } - let after=baseline.resource_snapshot();let expected=match name{"growth"|"add"=>size+1,"remove"=>size-1,"clear"=>0,_=>size}; - let capacity=validate_set(&baseline,&image,expected); - assert_eq!(capacity,if name=="growth"{16}else if name=="clear"{0}else{8}); - if name=="growth"{assert!(max_nodes>=13,"six old + six copied + inserted");assert!(max_tables>=2);} - if name=="duplicate"||name=="cursor"{assert_eq!(set_state(&baseline,&image),old);} - println!("SET PEAK {name}{suffix} nodes={max_nodes} tables={max_tables} before={:?} after={:?}",before.budget.peaks,after.budget.peaks); - let mut refusals=0;let mut structural_refusals=0; - for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::CallDepth] { - let lower=before.budget.peaks[resource as usize];let upper=after.budget.peaks[resource as usize];if lower>=upper{continue;} - let mut limits=vec![lower,lower+(upper-lower)/4,lower+(upper-lower)/2,upper-1]; - if resource==Q::HandleSlots{limits.extend(lower..upper.min(lower+24));}limits.sort_unstable();limits.dedup(); - for limit in limits { - let mut vm=prepare(RuntimeLimits::default().lowered(resource,limit).unwrap());let observer=vm.resource_observer(); - assert!(matches!(vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap().reason,End::Breakpoint),"Set setup {name} {resource:?}={limit}"); - let original=set_state(&vm,&image);vm.remove_breakpoint(before_pc); - let (report,prefix,_)=trace_collection_attempt(&mut vm,&original,after_pc);assert_mutation_prefix(&prefix,&successful); - if let End::Trap(info)=report.reason { - assert_eq!(info.code,TRAP_RESOURCE_LIMIT,"Set {name} {resource:?}={limit}: {info:?}"); - let touched=prefix.iter().any(|(_,state)|set_without_guard(state.clone(),&image)!=set_without_guard(original.clone(),&image)); - if !touched {assert_eq!(set_without_guard(observe_originals(&vm,&original),&image),set_without_guard(original.clone(),&image));} - if name=="cursor"{assert_eq!(set_state(&vm,&image),original);} - let now=observe_originals(&vm,&original);guard_effect|=!touched&&now!=original; - structural_refusals+=usize::from(touched); - let instruction=decode_next(info.pc as usize,image.code()).unwrap();table_refusal|=name=="growth"&&instruction.opcode==Op::ArrayNew; - if instruction.opcode==Op::StructNew { - let named=image.registry().declarations().types[instruction.imm_u32().unwrap() as usize].name.as_deref(); - node_refusal|=named==Some("_SetNode");snapshot_refusal|=named==Some("_SnapshotNode"); - } - refusals+=1;println!("SET PHASE REFUSAL {name}{suffix} structural={touched} resource={resource:?} limit={limit} opcode={:?}",instruction.opcode); - }else{assert!(matches!(report.reason,End::BudgetExhausted|End::Breakpoint)&&vm.pc()==after_pc);} - drop(vm);for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes]{assert_eq!(observer.used(q),0);} - } - } - assert!(refusals>0,"Set {name}: resource refusal evidence"); - println!("SET PHASE SUMMARY {name}{suffix} refusals={refusals} after_structural_write={structural_refusals}"); - } - } - assert!(node_refusal&&snapshot_refusal&&table_refusal&&guard_effect,"nodes/snapshot/table/guard refusal evidence required"); -} -fn verify_set_collection_gc(root:&std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - let bytes=std::fs::read(root.join("pbs-set-gc-collection.pbx")).expect("mandatory Set collection GC fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap();let mut previous=0; - for (round,count) in [64,61,0,0].into_iter().enumerate() { - let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::FrameSync),"Set GC {round}: {report:?}"); - let collections=vm.resource_snapshot().gc.collections;assert!(collections>previous);previous=collections; - let objects=vm.heap().diagnostic_typed_storage(); - for name in ["_SetNode","Item"] { - let actual=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count();assert_eq!(actual,count,"Set GC {round}: {name}"); - } - println!("SET COLLECTION/OLD-CANDIDATE GC PASS round={round} live_nodes={count}"); - } - let report=vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)]); -} - - -// Controlled test-only source instrumentation, never a production SDK algorithm. -// A quota probe is inserted after the real candidate-table store and before size. -// Natural production-quota coverage and its refusal frequencies remain separate. -fn verify_set_postpublication_injection(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q},resource_diagnostics::StorageValue as V}; - use prometeu_bytecode::{decode_next,isa::core::CoreOpCode as Op,TRAP_RESOURCE_LIMIT}; - for suffix in ["","-optimized"] { - let bytes=std::fs::read(root.join(format!("pbs-set-injected-refusal-growth{suffix}.pbx"))).expect("explicit test-only post-publication injection"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let limits=RuntimeLimits::default().lowered(Q::GuestBytes,500_000).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),limits);let observer=vm.resource_observer();vm.prepare_boot_call().unwrap(); - let mut found=false; - for _ in 0..200_000 { - let instruction=decode_next(vm.pc(),image.code()).unwrap(); - if instruction.opcode==Op::ArrayNew&&vm.operand_stack_top(1)==vec![Value::Int64(1_000_000)] { - let original=vm.heap().diagnostic_typed_storage();let state=set_state(&vm,&image); - let owner=state.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("set")).unwrap(); - assert_eq!(owner.groups[1],vec![V::Int64(6)]);assert_eq!(owner.groups[3],vec![V::Boolean(true)]); - assert_eq!(state.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_SetNode")).count(),7); - assert!(state.iter().any(|o|matches!(image.registry().declarations().types[o.type_id.0 as usize].kind,prometeu_bytecode::registry::TypeKind::Array(_))&&o.groups.len()==16)); - let input=vm.operand_stack_top(1).to_vec();let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - let End::Trap(info)=report.reason else{panic!("post-publication injection: {report:?}")};assert_eq!(info.code,TRAP_RESOURCE_LIMIT); - assert_eq!(vm.heap().diagnostic_typed_storage(),original,"refused probe preserves its entry state, retaining earlier table publication"); - assert_eq!(vm.operand_stack_top(1),input); - println!("SET TEST-ONLY POST-PUBLICATION QUOTA INJECTION PASS {suffix}: new table=16 nodes=7 old size=6 guard=true");found=true;break; - } - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::BudgetExhausted),"before injection: {report:?}"); - } - assert!(found);drop(vm);for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes]{assert_eq!(observer.used(q),0);} - } -} - - -fn verify_identity_negative_fixtures(root:&std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - use prometeu_bytecode::{decode_next,isa::core::CoreOpCode as Op}; - for base in ["bad-category","bad-right","dead-bad-category","bad-typeid"] { - for suffix in ["","-optimized"] { - let name=format!("common-identity-{base}{suffix}");let bytes=std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); - assert!(ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).is_err(),"{name}"); - println!("IDENTITY NEUTRAL ADMISSION REJECT PASS {name}"); - } - } - for base in ["partial","truncated"] { - let bytes=std::fs::read(root.join(format!("common-identity-{base}.pbx"))).unwrap(); - assert!(ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).is_err()); - println!("IDENTITY PARTIAL/TRUNCATED ADMISSION REJECT PASS {base}"); - } - for base in ["null-views","right-after-null","right-after-distinct"] { - let bytes=std::fs::read(root.join(format!("common-identity-{base}.pbx"))).unwrap(); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap_or_else(|e|panic!("{base}: {e:?}")); - let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap(); - loop { - let instruction=decode_next(vm.pc(),image.code()).unwrap(); - if instruction.opcode==Op::RefIdentityEq { - let operands=vm.operand_stack_top(3).to_vec(); - let zero=vm.run_budget(0,&mut NoNative,&mut HostContext::new(None)).unwrap();assert_eq!((zero.cycles_used,zero.steps_executed),(0,0)); - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap();assert_eq!(report.cycles_used,7); - if base=="null-views" { - assert!(matches!(report.reason,End::BudgetExhausted));assert_eq!(vm.operand_stack_top(1),vec![Value::Boolean(true)]); - }else { - let End::Trap(info)=report.reason else{panic!("{base}: right validation was skipped: {report:?}")}; - assert_eq!(info.code,prometeu_bytecode::TRAP_TYPE);assert_eq!(report.steps_executed,0);assert_eq!(vm.operand_stack_top(3),operands); - } - println!("IDENTITY COMPLETE RIGHT/NULL/FUEL/COST PASS {base}");break; - } - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::BudgetExhausted)); - } - } -} -fn verify_installed_hash(root:&std::path::Path) { - use prometeu_vm::LogicalFrameEndingReason as End; - let bytes=std::fs::read(root.join("pbs-hash-installed.pbx")).expect("mandatory installed hashing example"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image,Default::default());vm.prepare_boot_call().unwrap(); - let report=vm.run_budget(1_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - assert!(matches!(report.reason,End::FrameSync|End::Halted|End::EndOfRom),"installed hashing: {report:?}"); - println!("HASH INSTALLED JAR/SDK/EXAMPLE LOAD/EXEC PASS"); -} - - -fn map_state(vm:&VirtualMachine,image:&ValidatedProgramImage)->ObservedStorage { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let objects=vm.heap().diagnostic_typed_storage(); - let owner=objects.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("map")).expect("source Map"); - let mut pending=vec![owner.reference];let mut state:ObservedStorage=Vec::new(); - while let Some(reference)=pending.pop() { - if state.iter().any(|o|o.reference==reference){continue;} - let object=objects.iter().find(|o|o.reference==reference).expect("live complete Map group"); - for value in object.groups.iter().flatten(){if let V::Reference(reference)=value{pending.push(*reference);}} - state.push(object.clone()); - } - state.sort_by_key(|o|(o.reference.index,o.reference.generation));state -} -fn map_without_guard(mut state:ObservedStorage,image:&ValidatedProgramImage)->ObservedStorage { - for object in &mut state { - if image.registry().declarations().types[object.type_id.0 as usize].name.as_deref()==Some("map") { - object.groups[3]=vec![prometeu_vm::resource_diagnostics::StorageValue::Boolean(false)]; - } - } - state -} -fn validate_map(vm:&VirtualMachine,image:&ValidatedProgramImage,expected:i64)->usize { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let state=map_state(vm,image); - let owner=state.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("map")).unwrap(); - assert_eq!(owner.groups[1],vec![V::Int64(expected)]);assert_eq!(owner.groups[3],vec![V::Boolean(false)]); - let get=|reference|state.iter().find(|o|o.reference==reference).expect("reachable object"); - let V::Reference(carrier)=owner.groups[0][0] else{assert_eq!(expected,0);return 0;}; - let V::Reference(table)=get(carrier).groups[0][0] else{panic!("bucket carrier")}; - let buckets=get(table);let capacity=buckets.groups.len();let mut nodes=std::collections::HashSet::new(); - for (bucket,group) in buckets.groups.iter().enumerate() { - if *group==vec![V::Null,V::Null]{continue;} - let [V::Int64(tag),V::Reference(first)]=group.as_slice() else{panic!("complete bucket group")}; - assert_eq!(image.registry().declarations().types[*tag as usize].name.as_deref(),Some("_MapNode")); - let mut next=Some(*first); - while let Some(reference)=next { - assert!(nodes.insert(reference),"each node appears once, no cycles");let node=get(reference); - let V::Int64(hash)=node.groups[0][0] else{panic!("cached complete hash")}; - assert_eq!(hash.rem_euclid(capacity as i64) as usize,bucket); - next=match node.groups[3][0]{V::Null=>None,V::Reference(carrier)=>{let V::Reference(value)=get(carrier).groups[0][0] else{panic!("next node carrier")};Some(value)},_=>panic!("next group")}; - } - } - assert_eq!(nodes.len(),expected as usize);capacity -} -fn verify_map_refusals(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q}}; - use prometeu_bytecode::{decode_next,isa::core::CoreOpCode as Op,TRAP_RESOURCE_LIMIT}; - let mut node_refusal=false;let mut snapshot_refusal=false;let mut table_refusal=false;let mut guard_effect=false; - for name in ["growth","add","replace","put","remove","clear","cursor","read"] { - for suffix in ["","-optimized"] { - let bytes=std::fs::read(root.join(format!("pbs-map-refusal-{name}{suffix}.pbx"))).expect("mandatory Map resource fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let marker=|value:i32|{let mut pc=0;let mut found=Vec::new();while pc")).count()); - max_tables=max_tables.max(objects.iter().filter(|o|matches!(image.registry().declarations().types[o.type_id.0 as usize].kind,prometeu_bytecode::registry::TypeKind::Array(_))).count()); - successful.push((baseline.pc(),observe_originals(&baseline,&old))); - let report=baseline.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if baseline.pc()==after_pc{break;} - assert!(matches!(report.reason,End::BudgetExhausted),"Map {name}: {report:?}");assert!(successful.len()<200_000); - } - let after=baseline.resource_snapshot();let expected=match name{"growth"|"add"=>size+1,"remove"=>size-1,"clear"=>0,_=>size}; - let capacity=validate_map(&baseline,&image,expected); - assert_eq!(capacity,if name=="growth"{16}else if name=="clear"{0}else{8}); - if name=="replace"||name=="put"{let state=map_state(&baseline,&image);assert!(state.iter().any(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_MapNode")&&o.groups[1]==vec![prometeu_vm::resource_diagnostics::StorageValue::Int32(1)]&&o.groups[2]==vec![prometeu_vm::resource_diagnostics::StorageValue::Int32(42)]));} - if name=="growth"{assert!(max_nodes>=13,"six old + six copied + inserted");assert!(max_tables>=2);} - if name=="read"||name=="cursor"{assert_eq!(map_state(&baseline,&image),old);} - println!("MAP PEAK {name}{suffix} nodes={max_nodes} tables={max_tables} before={:?} after={:?}",before.budget.peaks,after.budget.peaks); - let mut refusals=0;let mut structural_refusals=0; - for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::CallDepth] { - let lower=before.budget.peaks[resource as usize];let upper=after.budget.peaks[resource as usize];if lower>=upper{continue;} - let mut limits=vec![lower,lower+(upper-lower)/4,lower+(upper-lower)/2,upper-1]; - if resource==Q::HandleSlots{limits.extend(lower..upper.min(lower+24));}limits.sort_unstable();limits.dedup(); - for limit in limits { - let mut vm=prepare(RuntimeLimits::default().lowered(resource,limit).unwrap());let observer=vm.resource_observer(); - assert!(matches!(vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap().reason,End::Breakpoint),"Map setup {name} {resource:?}={limit}"); - let original=map_state(&vm,&image);vm.remove_breakpoint(before_pc); - let (report,prefix,_)=trace_collection_attempt(&mut vm,&original,after_pc);assert_mutation_prefix(&prefix,&successful); - if let End::Trap(info)=report.reason { - assert_eq!(info.code,TRAP_RESOURCE_LIMIT,"Map {name} {resource:?}={limit}: {info:?}"); - let touched=prefix.iter().any(|(_,state)|map_without_guard(state.clone(),&image)!=map_without_guard(original.clone(),&image)); - if !touched {assert_eq!(map_without_guard(observe_originals(&vm,&original),&image),map_without_guard(original.clone(),&image));} - if name=="cursor"{assert_eq!(map_state(&vm,&image),original);} - let now=observe_originals(&vm,&original);guard_effect|=!touched&&now!=original; - structural_refusals+=usize::from(touched); - let instruction=decode_next(info.pc as usize,image.code()).unwrap();table_refusal|=name=="growth"&&instruction.opcode==Op::ArrayNew; - if instruction.opcode==Op::StructNew { - let named=image.registry().declarations().types[instruction.imm_u32().unwrap() as usize].name.as_deref(); - node_refusal|=named==Some("_MapNode");snapshot_refusal|=named==Some("_SnapshotNode>"); - } - refusals+=1;println!("MAP PHASE REFUSAL {name}{suffix} structural={touched} resource={resource:?} limit={limit} opcode={:?}",instruction.opcode); - }else{assert!(matches!(report.reason,End::BudgetExhausted|End::Breakpoint)&&vm.pc()==after_pc);} - drop(vm);for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes]{assert_eq!(observer.used(q),0);} - } - } - assert!(refusals>0,"Map {name}: resource refusal evidence"); - println!("MAP PHASE SUMMARY {name}{suffix} refusals={refusals} after_structural_write={structural_refusals}"); - } - } - assert!(node_refusal&&snapshot_refusal&&table_refusal&&guard_effect,"nodes/snapshot/table/guard refusal evidence required"); -} -fn verify_map_collection_gc(root:&std::path::Path) { - for suffix in ["","-optimized"] {verify_map_collection_gc_variant(root,suffix);} -} -fn verify_map_collection_gc_variant(root:&std::path::Path,suffix:&str) { - use prometeu_vm::LogicalFrameEndingReason as End; - let bytes=std::fs::read(root.join(format!("pbs-map-gc-collection{suffix}.pbx"))).expect("mandatory Map collection GC fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap();let mut previous=0; - for (round,count) in [64,64,61,0,0].into_iter().enumerate() { - let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::FrameSync),"Map GC {round}: {report:?}"); - let collections=vm.resource_snapshot().gc.collections;assert!(collections>previous);previous=collections; - let objects=vm.heap().diagnostic_typed_storage(); - for name in ["_MapNode","Item"] { - let actual=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count();assert_eq!(actual,if name=="Item"{count*2}else{count},"Map GC {round}: {name}"); - } - println!("MAP COLLECTION/OLD-CANDIDATE GC PASS {suffix} round={round} live_nodes={count}"); - } - let report=vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)]); -} - - -// Controlled test-only source instrumentation, never a production SDK algorithm. -// A quota probe is inserted after the real candidate-table store and before size. -// Natural production-quota coverage and its refusal frequencies remain separate. -fn verify_map_postpublication_injection(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q},resource_diagnostics::StorageValue as V}; - use prometeu_bytecode::{decode_next,isa::core::CoreOpCode as Op,TRAP_RESOURCE_LIMIT}; - for suffix in ["","-optimized"] { - let bytes=std::fs::read(root.join(format!("pbs-map-injected-refusal-growth{suffix}.pbx"))).expect("explicit test-only post-publication injection"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let limits=RuntimeLimits::default().lowered(Q::GuestBytes,500_000).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),limits);let observer=vm.resource_observer();vm.prepare_boot_call().unwrap(); - let mut found=false; - for _ in 0..200_000 { - let instruction=decode_next(vm.pc(),image.code()).unwrap(); - if instruction.opcode==Op::ArrayNew&&vm.operand_stack_top(1)==vec![Value::Int64(1_000_000)] { - let original=vm.heap().diagnostic_typed_storage();let state=map_state(&vm,&image); - let owner=state.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("map")).unwrap(); - assert_eq!(owner.groups[1],vec![V::Int64(6)]);assert_eq!(owner.groups[3],vec![V::Boolean(true)]); - assert_eq!(state.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_MapNode")).count(),7); - assert!(state.iter().any(|o|matches!(image.registry().declarations().types[o.type_id.0 as usize].kind,prometeu_bytecode::registry::TypeKind::Array(_))&&o.groups.len()==16)); - let input=vm.operand_stack_top(1).to_vec();let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap(); - let End::Trap(info)=report.reason else{panic!("post-publication injection: {report:?}")};assert_eq!(info.code,TRAP_RESOURCE_LIMIT); - assert_eq!(vm.heap().diagnostic_typed_storage(),original,"refused probe preserves its entry state, retaining earlier table publication"); - assert_eq!(vm.operand_stack_top(1),input); - println!("MAP TEST-ONLY POST-PUBLICATION QUOTA INJECTION PASS {suffix}: new table=16 nodes=7 old size=6 guard=true");found=true;break; - } - let report=vm.run_budget(1,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::BudgetExhausted),"before injection: {report:?}"); - } - assert!(found);drop(vm);for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes]{assert_eq!(observer.used(q),0);} - } -} - -fn verify_pbs_map_fixtures(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeResource as Q}; - let successes=["basic","optional","scalars","objects","references","content","collisions","arithmetic", - "tuple","native","pixel","random","cursor-empty","cursor-single","snapshot","evaluation","callback-reads"]; - let faults=(1..=7).map(|n|(format!("fault-callback-{n}"),if n==7{prometeu_bytecode::TRAP_DIV_ZERO}else{prometeu_bytecode::TRAP_EXPLICIT})) - .chain((1..=7).map(|n|(format!("fault-equals-{n}"),if n==7{prometeu_bytecode::TRAP_DIV_ZERO}else{prometeu_bytecode::TRAP_EXPLICIT}))) - .chain(std::iter::once(("fault-overflow".to_string(),prometeu_bytecode::TRAP_EXPLICIT))); - let mut count=0; - for (base,fault) in successes.into_iter().map(|n|(n.to_string(),None)).chain(faults.map(|(n,f)|(n,Some(f)))) { - for suffix in ["","-optimized"] { - let name=format!("{base}{suffix}");let bytes=std::fs::read(root.join(format!("pbs-map-{name}.pbx"))).unwrap_or_else(|e|panic!("mandatory Map {name}: {e}")); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap_or_else(|e|panic!("Map {name}: {e:?}")); - let registry=image.registry().clone();let mut vm=VirtualMachine::from_image(image,Default::default());let observer=vm.resource_observer(); - vm.prepare_boot_call().unwrap();let report=vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); - if let Some(code)=fault { - let End::Trap(info)=report.reason else{panic!("{name}: {report:?}")};assert_eq!(info.code,code,"{name}: {info:?}"); - if base.starts_with("fault-callback")||base.starts_with("fault-equals") { - use prometeu_vm::resource_diagnostics::StorageValue as V; - let objects=vm.heap().diagnostic_typed_storage(); - let owner=objects.iter().find(|o|registry.declarations().types[o.type_id.0 as usize].name.as_deref()==Some("map")).expect("faulted Map retained"); - let populated=base.starts_with("fault-equals"); - assert_eq!(owner.groups[1],vec![V::Int64(if populated{1}else{0})]);assert_eq!(owner.groups[3],vec![V::Boolean(true)]); - if populated{assert!(objects.iter().any(|o|registry.declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_MapNode")&&o.groups[1]==vec![V::Int32(0)]&&o.groups[2]==vec![V::Int32(20)]));} - else{assert_eq!(owner.groups[0],vec![V::Null]);} - } - } else {assert!(matches!(report.reason,End::Halted|End::EndOfRom),"{name}: {report:?}");assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)],"{name}");} - drop(vm);for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations]{assert_eq!(observer.used(q),0,"{name}: owner release {q:?}");} - count+=1;println!("MAP SOURCE/LOAD/EXEC/GUARD PASS {name}"); - } - } - println!("MAP MANDATORY SOURCE CASES {count}"); - verify_map_refusals(root);verify_map_postpublication_injection(root);verify_map_cursor_gc(root);verify_map_collection_gc(root);verify_map_distribution(root); -} - -fn verify_map_cursor_gc(root:&std::path::Path) { - for suffix in ["","-optimized"] {verify_map_cursor_gc_variant(root,suffix);} -} -fn verify_map_cursor_gc_variant(root:&std::path::Path,suffix:&str) { - use prometeu_vm::LogicalFrameEndingReason as End; - let bytes=std::fs::read(root.join(format!("pbs-map-gc{suffix}.pbx"))).expect("mandatory Map snapshot GC fixture"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap();let mut previous=0; - for (round,count) in [1200,1,1,0].into_iter().enumerate() { - let report=vm.run_budget(100_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::FrameSync),"Map cursor GC {round}: {report:?}"); - let snapshot=vm.resource_snapshot();assert!(snapshot.gc.collections>previous);previous=snapshot.gc.collections; - let objects=vm.heap().diagnostic_typed_storage(); - assert!(!objects.iter().any(|o|matches!(image.registry().declarations().types[o.type_id.0 as usize].kind,prometeu_bytecode::registry::TypeKind::Array(_))),"snapshot retains no Map table"); - for (name,expected) in [("_SnapshotNode>",count),("keyval",count),("Item",count*2),("_MapNode",0)] { - assert_eq!(objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count(),expected,"Map cursor GC {round}: {name}"); - } - println!("MAP CURSOR/KEYVAL/KEY/VALUE GC PASS {suffix} round={round} nodes={count} items={}",count*2); - } - let report=vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)]); -} - -fn verify_map_distribution(root:&std::path::Path) { - use prometeu_vm::{LogicalFrameEndingReason as End,resource_diagnostics::StorageValue as V}; - for name in ["imports","installed"] { - let bytes=std::fs::read(root.join(format!("pbs-map-{name}.pbx"))).expect("mandatory Map workspace/installed example"); - let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); - let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap(); - let report=vm.run_budget(2_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::FrameSync|End::Halted|End::EndOfRom),"Map distribution {name}: {report:?}"); - let objects=vm.heap().diagnostic_typed_storage(); - let cursors=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_SnapshotCursor>")).collect::>(); - assert!(!cursors.is_empty(),"installed/imported Map actually constructs the common entry Cursor"); - let get=|r|objects.iter().find(|o|o.reference==r).unwrap(); - for cursor in cursors { - let V::Reference(carrier)=cursor.groups[0][0] else{panic!("current carrier")};let V::Reference(node)=get(carrier).groups[0][0] else{panic!("node")}; - assert_eq!(get(node).groups[1],vec![V::Null],"complete traversal retains sticky final node"); - let V::Reference(entry)=get(node).groups[0][0] else{panic!("captured keyval")}; - assert_eq!(image.registry().declarations().types[get(entry).type_id.0 as usize].name.as_deref(),Some("keyval")); - } - println!("MAP DISTRIBUTION SOURCE/LOAD/EXEC PASS {name}"); - } -} diff --git a/tools/pbx-conformance/memcard.rs b/tools/pbx-conformance/memcard.rs deleted file mode 100644 index f09719ab..00000000 --- a/tools/pbx-conformance/memcard.rs +++ /dev/null @@ -1,533 +0,0 @@ -//! Native production Firmware/SystemOS evidence; never a claim about the installed process protocol. -use prometeu_drivers::{TestPlatform, memcard::FileMemcard}; -use prometeu_firmware::firmware::{Firmware, FirmwareState}; -use prometeu_hal::{ - InputSignals, - app_mode::AppMode, - cartridge::{AssetsPayloadSource, Cartridge}, - memcard::{MemcardIoError, MemcardStorage}, -}; -use prometeu_system::memcard::{ - admission::PreparationState, - image::IMAGE_BYTES, - session::{Mode, RequestState}, - transaction::Card, -}; -use std::{ - path::Path, - time::{Duration, Instant}, -}; - -const APP: u32 = 1296387395; -const PAYLOAD: [u8; 4] = [0, 127, 128, 255]; -fn fresh(path: &Path) -> FileMemcard { - FileMemcard::create(path, IMAGE_BYTES, |io, id| { - Card::format(io, id).map_err(|_| MemcardIoError::IoError) - }) - .unwrap() -} -fn start( - root: &Path, - name: &str, - storage: Option>, - choice: InputSignals, -) -> (Firmware, TestPlatform) { - start_slots(root, name, storage, choice, 1) -} -fn start_slots( - root: &Path, - name: &str, - storage: Option>, - choice: InputSignals, - slots: u8, -) -> (Firmware, TestPlatform) { - let mut fw = Firmware::new(None); - let mut platform = TestPlatform::new(); - fw.os.poll_background_io(&mut platform); - if let Some(storage) = storage { - fw.os.memcard().mount_card(storage).unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); - while !fw.os.memcard().card_installed() { - fw.os.poll_background_io(&mut platform); - assert!( - !matches!(fw.os.memcard().admission.state, PreparationState::Failed(_)), - "mount failed: {:?}", - fw.os.memcard().admission.state - ); - assert!(Instant::now() < deadline); - std::thread::sleep(Duration::from_millis(1)); - } - } - fw.load_cartridge(Cartridge { - app_id: APP, - title: "Studio memcard".into(), - app_version: "1".into(), - app_mode: AppMode::Game, - capabilities: super::caps::MEMCARD, - memcard_slots: Some(slots), - program: std::fs::read(root.join(format!("{name}.pbx"))).unwrap(), - assets: AssetsPayloadSource::empty(), - asset_table: vec![], - preload: vec![], - }); - fw.tick(&InputSignals::default(), &mut platform); - fw.tick(&choice, &mut platform); - (fw, platform) -} -fn run(fw: &mut Firmware, platform: &mut TestPlatform, frames: usize) { - for _ in 0..frames { - fw.tick(&InputSignals::default(), platform); - assert!( - !matches!(fw.state, FirmwareState::AppCrashes(_)), - "guest crashed: {:?}", - fw.state - ); - std::thread::sleep(Duration::from_millis(1)); - } - let deadline = Instant::now() + Duration::from_secs(2); - while worker_pending(fw) { - assert!(Instant::now() < deadline, "native worker did not settle"); - fw.tick(&InputSignals::default(), platform); - assert!( - !matches!(fw.state, FirmwareState::AppCrashes(_)), - "guest crashed: {:?}", - fw.state - ); - std::thread::sleep(Duration::from_millis(1)); - } -} -fn worker_pending(fw: &mut Firmware) -> bool { - let mem = fw.os.memcard(); - let telemetry = mem.lane.telemetry(); - let context = mem.session.context(); - mem.admission.state == PreparationState::Pending - || telemetry.active_job_id.is_some() - || telemetry.pending_depth != 0 - || (1..=8).any(|id| { - mem.session - .query(context, id) - .is_ok_and(|r| r.state == RequestState::Pending) - }) -} -fn assert_ram(fw: &mut Firmware, dirty: bool) { - let session = &mut fw.os.memcard().session; - let context = session.context(); - let mut bytes = [0; 4]; - assert_eq!(session.read(context, 0, 0, &mut bytes).unwrap(), 4); - assert_eq!(bytes, PAYLOAD); - assert_eq!(session.descriptor(context, 0).unwrap().2, dirty); -} -struct Fault { - inner: FileMemcard, - kind: u8, - payload: bool, -} -impl MemcardStorage for Fault { - fn len(&self) -> Result { - self.inner.len() - } - fn read_only(&self) -> bool { - self.inner.read_only() - } - fn read_at(&mut self, o: u64, b: &mut [u8]) -> Result<(), MemcardIoError> { - self.inner.read_at(o, b) - } - fn write_at(&mut self, o: u64, b: &[u8]) -> Result<(), MemcardIoError> { - if o >= 802816 { - self.payload = true; - if self.kind == 1 { - return Err(MemcardIoError::IoError); - } - } - self.inner.write_at(o, b)?; - if self.kind == 2 && self.payload && (o == 8192 || o == 12288) { - self.inner.sync()?; - return Err(MemcardIoError::IoError); - } - Ok(()) - } - fn sync(&mut self) -> Result<(), MemcardIoError> { - self.inner.sync() - } -} -pub fn verify(root: &Path) { - let work = std::env::temp_dir().join(format!("studio-memcard-native-{}", std::process::id())); - std::fs::create_dir_all(&work).unwrap(); - let abi = std::fs::read(root.join("pbs-memcard-abi.pbx")).unwrap(); - super::ValidatedProgramImage::load( - &abi, - &mut super::LoadBudget::new(Default::default()), - super::caps::MEMCARD, - ) - .unwrap(); - println!("NATIVE LOAD PASS all 14 mem imports against the production loader"); - for suffix in ["", "-optimized"] { - let name = format!("pbs-memcard-example{suffix}"); - let path = work.join(format!("save{suffix}.pmc")); - let (mut fw, mut p) = start( - root, - &name, - Some(Box::new(fresh(&path))), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut fw, &mut p, 100); - assert_ram(&mut fw, false); - assert_eq!(fw.os.memcard().session.mode(), Some(Mode::Persistent)); - drop(fw); - let mut card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap(); - let slot = card - .catalog - .games - .iter() - .find(|g| g.app_id == APP) - .unwrap() - .slots[0] as usize; - let generation = card.current().slots[slot].generation; - let mut bytes = [0; 4]; - assert_eq!(card.read_slot(slot, &mut bytes).unwrap(), 4); - assert_eq!(bytes, PAYLOAD); - drop(card); - let (mut reopened, mut p) = start( - root, - &name, - Some(Box::new(FileMemcard::open(&path, false).unwrap())), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut reopened, &mut p, 100); - assert_ram(&mut reopened, false); - drop(reopened); - let card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap(); - assert_eq!( - card.current().slots[slot].generation, - generation, - "reopen must read, not resave" - ); - drop(card); - let (mut memory, mut p) = start( - root, - &name, - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - ); - run(&mut memory, &mut p, 100); - assert_ram(&mut memory, true); - assert_eq!(memory.os.memcard().session.mode(), Some(Mode::MemoryOnly)); - memory.request_home_from_host(); - run(&mut memory, &mut p, 4); - assert!(memory.resume_resident_game_from_home()); - run(&mut memory, &mut p, 4); - assert_ram(&mut memory, true); - println!( - "NATIVE PASS {name}: exact save/reopen, no resave, memory-only; not installed-process evidence" - ); - let name = format!("pbs-memcard-contract{suffix}"); - let path = work.join(format!("contract{suffix}.pmc")); - let (mut contract, mut p) = start( - root, - &name, - Some(Box::new(fresh(&path))), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut contract, &mut p, 100); - assert_ram(&mut contract, false); - println!( - "NATIVE PASS {name}: zero initialization, aliases, ordinary-array vacancy, domain errors/status-first Null payloads" - ); - let name = format!("pbs-memcard-alias{suffix}"); - let (mut alias, mut p) = start( - root, - &name, - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - ); - run(&mut alias, &mut p, 100); - assert_ram(&mut alias, true); - println!( - "NATIVE PASS {name}: imported type/service aliases retain native carrier and forwarding" - ); - let name = format!("pbs-memcard-imports{suffix}"); - let (mut imports, mut p) = start( - root, - &name, - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - ); - run(&mut imports, &mut p, 100); - let context = imports.os.memcard().session.context(); - assert_eq!( - imports - .os - .memcard() - .session - .presentation(context) - .unwrap() - .unwrap() - .title, - "Imported hook" - ); - println!( - "NATIVE PASS {name}: one canonical imported role, initialized dependencies, retained target" - ); - let name = format!("pbs-memcard-busy{suffix}"); - let path = work.join(format!("busy{suffix}.pmc")); - let (mut busy, mut p) = start( - root, - &name, - Some(Box::new(fresh(&path))), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut busy, &mut p, 100); - assert_ram(&mut busy, false); - println!("NATIVE PASS {name}: committing source rejects write/clear/second commit"); - let name = format!("pbs-memcard-clear{suffix}"); - let path = work.join(format!("clear{suffix}.pmc")); - let (mut clear, mut p) = start( - root, - &name, - Some(Box::new(fresh(&path))), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut clear, &mut p, 100); - let context = clear.os.memcard().session.context(); - let (descriptor, used, dirty) = clear.os.memcard().session.descriptor(context, 0).unwrap(); - assert_eq!(used, 0); - assert_eq!(descriptor.generation, 2); - assert!(!dirty); - drop(clear); - let mut card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap(); - let slot = card - .catalog - .games - .iter() - .find(|g| g.app_id == APP) - .unwrap() - .slots[0] as usize; - assert_eq!(card.read_slot(slot, &mut [0; 4]).unwrap(), 0); - println!("NATIVE PASS {name}: explicit clear commit survives remount"); - let name = format!("pbs-memcard-publish{suffix}"); - let path = work.join(format!("publish{suffix}.pmc")); - let (mut public, mut p) = start( - root, - &name, - Some(Box::new(fresh(&path))), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut public, &mut p, 100); - assert_ram(&mut public, false); - let context = public.os.memcard().session.context(); - let result = (1..=8) - .find_map(|id| public.os.memcard().session.query(context, id).ok()) - .unwrap(); - assert_eq!(result.state, RequestState::Success); - drop(public); - let mut card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap(); - let game = card.catalog.games.iter().find(|g| g.app_id == APP).unwrap(); - assert_eq!(game.title, "Updated presentation"); - assert_eq!(game.data_format_version, 2); - assert_eq!(card.read_icon(APP).unwrap(), vec![0; 560]); - println!("NATIVE PASS {name}: public title/format/icon publication and retained request"); - let name = format!("pbs-memcard-transfer-limit{suffix}"); - let (mut transfer, mut p) = start( - root, - &name, - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - ); - run(&mut transfer, &mut p, 100); - let session = &mut transfer.os.memcard().session; - let context = session.context(); - assert_eq!(session.descriptor(context, 0).unwrap().1, 4096); - let mut last = [0]; - assert_eq!(session.read(context, 0, 4095, &mut last).unwrap(), 1); - assert_eq!(last, [255]); - println!("NATIVE PASS {name}: exact 4096-byte transfer and byte 255"); - let name = format!("pbs-memcard-example{suffix}"); - let (mut full, mut p) = start_slots( - root, - &name, - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - 64, - ); - run(&mut full, &mut p, 100); - assert_eq!(full.os.memcard().session.count(), 64); - assert_ram(&mut full, true); - println!("NATIVE PASS {name}: 64-slot admission"); - } - for (kind, expected) in [(1, RequestState::Failure), (2, RequestState::Indeterminate)] { - for suffix in ["", "-optimized"] { - let path = work.join(format!("fault-{kind}{suffix}.pmc")); - let fault = Fault { - inner: fresh(&path), - kind, - payload: false, - }; - let (mut fw, mut p) = start( - root, - &format!("pbs-memcard-retained{suffix}"), - Some(Box::new(fault)), - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut fw, &mut p, 100); - let session = &mut fw.os.memcard().session; - let context = session.context(); - let result = (1..=8) - .find_map(|id| session.query(context, id).ok()) - .expect("one retained guest request"); - assert_eq!(result.state, expected); - assert!(session.descriptor(context, 0).unwrap().2); - println!( - "NATIVE PASS PBS facade query{suffix}: {expected:?}, request {}, dirty RAM preserved", - result.id - ); - } - } - for name in [ - "pbs-memcard-inconsistent", - "pbs-memcard-trap", - "pbs-memcard-fuel", - "pbs-memcard-capacity-negative", - "pbs-memcard-capacity-overflow", - "pbs-memcard-read-bounds", - "pbs-memcard-write-bounds", - "pbs-memcard-byte-negative", - "pbs-memcard-byte-overflow", - "pbs-memcard-transfer-overflow", - ] { - for suffix in ["", "-optimized"] { - let name = format!("{name}{suffix}"); - let (mut fw, mut p) = start( - root, - &name, - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - ); - for _ in 0..150 { - fw.tick(&InputSignals::default(), &mut p); - if matches!(fw.state, FirmwareState::AppCrashes(_)) { - break; - } - std::thread::sleep(Duration::from_millis(1)); - } - assert!( - matches!(fw.state, FirmwareState::AppCrashes(_)), - "{name} must block admission" - ); - if let Some(task) = fw.os.lifecycle().resident_game_task() { - let sessions = fw.os.sessions(); - let session = sessions.vm_session_for_task(task).unwrap(); - assert_eq!( - session - .runtime - .atomic_telemetry - .completed_logical_frames - .load(std::sync::atomic::Ordering::Relaxed), - 0 - ); - } - println!("NATIVE PASS {name}: trap/failure, no completed gameplay frame"); - } - } - let path = work.join("readonly.pmc"); - drop(fresh(&path)); - for storage in [ - None, - Some(Box::new(FileMemcard::open(&path, true).unwrap()) as Box), - ] { - let (mut fw, mut p) = start( - root, - "pbs-memcard-example", - storage, - InputSignals { - a_signal: true, - ..Default::default() - }, - ); - run(&mut fw, &mut p, 20); - assert!(matches!(fw.state, FirmwareState::LoadCartridge(_))); - assert_eq!( - fw.os.memcard().session.mode(), - None, - "must not silently fall back to RAM" - ); - } - println!("NATIVE PASS absent/read-only: explicit choice retained; no memory fallback"); - let corrupt = work.join("corrupt.pmc"); - drop(fresh(&corrupt)); - let mut bytes = std::fs::read(&corrupt).unwrap(); - bytes[8192..16384].fill(0); - std::fs::write(&corrupt, &bytes).unwrap(); - let mut fw = Firmware::new(None); - let mut p = TestPlatform::new(); - fw.os.poll_background_io(&mut p); - fw.os - .memcard() - .mount_card(Box::new(FileMemcard::open(&corrupt, false).unwrap())) - .unwrap(); - let deadline = Instant::now() + Duration::from_secs(2); - while fw.os.memcard().admission.state == PreparationState::Pending { - fw.os.poll_background_io(&mut p); - assert!(Instant::now() < deadline); - std::thread::sleep(Duration::from_millis(1)); - } - assert_eq!( - fw.os.memcard().admission.state, - PreparationState::Failed(prometeu_system::memcard::image::Error::Corrupt) - ); - assert_eq!(std::fs::read(&corrupt).unwrap(), bytes); - println!("NATIVE PASS corrupt media: rejected without replacing with empty data"); - let (mut installed, mut p) = start( - root, - "pbs-memcard-installed", - None, - InputSignals { - x_signal: true, - ..Default::default() - }, - ); - run(&mut installed, &mut p, 100); - assert_ram(&mut installed, true); - println!( - "NATIVE PASS installed-JAR PBS example: native Firmware/SystemOS execution, not installed runtime process" - ); - std::fs::remove_dir_all(work).unwrap(); -} diff --git a/tools/pbx-conformance/result.rs b/tools/pbx-conformance/result.rs deleted file mode 100644 index 363539d4..00000000 --- a/tools/pbx-conformance/result.rs +++ /dev/null @@ -1,56 +0,0 @@ -//! PBS result groups execute on the unchanged production loader and VM. -use super::*; -use prometeu_vm::LogicalFrameEndingReason as End; -use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op}; - -pub fn verify(root: &std::path::Path) { - let cases = [ - ("unit-ok", vec![Value::Int32(0)]), - ("unit-err", vec![Value::Int32(2)]), - ("scalar", vec![Value::Int32(0), Value::Int32(42)]), - ("error", vec![Value::Int32(1), Value::Int64(0)]), - ("tuple", vec![Value::Int32(0), Value::Int64(9_007_199_254_740_993), Value::Int32(42)]), - ("reference", vec![Value::Int32(2), Value::Null]), - ("propagate", vec![Value::Int32(2), Value::Int64(0), Value::Null]), - ("nested", vec![Value::Int32(2), Value::Int32(0)]), - ("recover", vec![Value::Int32(0), Value::Int32(42)]), - ("remap", vec![Value::Int32(2), Value::Int32(0)]), - ("success", vec![Value::Int32(0), Value::Int32(42)]), - ("trait", vec![Value::Int32(1), Value::Null, Value::Null]), - ("fn", vec![Value::Int32(1), Value::Null]), - ("once", vec![Value::Int32(0), Value::Int32(42)]), - ("block-remap", vec![Value::Int32(2), Value::Int32(0)]), - ("reference-ok", vec![Value::Int32(0), Value::Int32(42)]), - ("fn-ok", vec![Value::Int32(0), Value::Int32(42)]), - ("trait-ok", vec![Value::Int32(0), Value::Int32(42)]), - ("color-ok", vec![Value::Int32(0), Value::Int64(42)]), - ("color-err", vec![Value::Int32(1), Value::Int64(0)]), - ("trap", vec![]), - ]; - let manifest = std::fs::read_to_string(root.join("pbs-result-manifest.txt")).expect("mandatory result manifest"); - assert_eq!(manifest.lines().count(), cases.len() * 2); - for (name, expected) in cases { for suffix in ["", "-optimized"] { - let bytes = std::fs::read(root.join(format!("pbs-result-{name}{suffix}.pbx"))).expect("mandatory result fixture"); - let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) - .unwrap_or_else(|e| panic!("result/{name}{suffix}: load {e:?}")); - let mut vm = VirtualMachine::from_image(image.clone(), Default::default()); - vm.prepare_boot_call().unwrap(); - let mut allocations = 0; - let mut trapped=false; - for step in 0..100_000 { - let instruction = decode_next(vm.pc(), image.code()).unwrap(); - if matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; } - let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None)) - .unwrap_or_else(|e| panic!("result/{name}{suffix}: run {e:?}")); - if matches!(report.reason, End::Trap(_)) && name=="trap" { trapped=true;break; } - if matches!(report.reason, End::Halted | End::EndOfRom) { break; } - assert!(matches!(report.reason, End::BudgetExhausted), "result/{name}{suffix}: {report:?}"); - assert!(step < 99_999, "result failed to terminate"); - } - if name=="trap" { assert!(trapped,"handle must not recover a VM trap");println!("RESULT TRAP PASS {suffix}");continue; } - assert_eq!(vm.operand_stack_top(expected.len()).iter().rev().cloned().collect::>(), expected, "result/{name}{suffix}"); - if matches!(name,"reference-ok"|"fn-ok"|"trait-ok") { assert!(allocations>0,"successful payload is constructed"); } - else { assert_eq!(allocations, 0, "result/{name}{suffix}: no holder or inactive payload allocations"); } - println!("RESULT PASS {name}{suffix} group={expected:?} executed_allocations={allocations}"); - } } -} diff --git a/tools/pbx-conformance/run.py b/tools/pbx-conformance/run.py deleted file mode 100644 index 75b8d06d..00000000 --- a/tools/pbx-conformance/run.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Build a production-loader harness without writing into the runtime checkout.""" -import argparse -import hashlib -import json -import pathlib -import platform -import subprocess -import tempfile - -parser = argparse.ArgumentParser() -parser.add_argument("--runtime", type=pathlib.Path, default=pathlib.Path("../runtime")) -parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prometeu-compiler/prometeu-build-pipeline/build/registry-conformance")) -parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies") -parser.add_argument("--animation-only", action="store_true", help="Run mandatory PBS core animation corpus") -parser.add_argument("--result-only", action="store_true", help="Run mandatory PBS result return-group corpus") -parser.add_argument("--memcard-only", action="store_true", help="Run PBS memcard through production Firmware/SystemOS (native, not installed process)") -parser.add_argument("--lifecycle-only", action="store_true", help="Run PBS guest lifecycle VM and production firmware corpus") -parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness") -parser.add_argument("--set-only", action="store_true", help="Run mandatory PBS Set corpus") -parser.add_argument("--map-only", action="store_true", help="Run mandatory PBS Map/Keyval corpus") -parser.add_argument("--stack-queue-only", action="store_true", help="Run mandatory PBS Stack/Queue corpus") -parser.add_argument("--identity-hashing-only", action="store_true", help="Run mandatory neutral and PBS identity/hash corpus") -parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only") -parser.add_argument("--random-only", action="store_true", help="Run the complete PBS Random corpus only") -parser.add_argument("--generic-contracts-only", action="store_true", help="Run the mandatory generic-contract source corpus only") -parser.add_argument("--linked-only", action="store_true", help="Run mandatory SDK Linked corpus only") -parser.add_argument("--list-cursor-only", action="store_true", help="Run the mandatory SDK List/Cursor corpus only") -parser.add_argument("--generic-structs-only", action="store_true", help="Run the mandatory generic-struct/function source corpus only") -args = parser.parse_args() -runtime = args.runtime.resolve() -if not args.math_only: - provider_vectors = runtime / "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv" - consumer_vectors = pathlib.Path("prometeu-architecture-tests/src/test/resources/random/random-conformance.tsv") - if provider_vectors.read_bytes() != consumer_vectors.read_bytes(): - raise SystemExit("Random oracle differs from the selected provider; update provenance and requalify") -provider_hash_vectors = runtime / "crates/console/prometeu-vm/tests/fixtures/hash-conformance.tsv" -consumer_hash_vectors = pathlib.Path("prometeu-architecture-tests/src/test/resources/hash/hash-conformance.tsv") -if provider_hash_vectors.read_bytes() != consumer_hash_vectors.read_bytes(): - raise SystemExit("Hash oracle differs from selected provider") -print(subprocess.check_output(["rustc", "-Vv"], text=True).strip(), flush=True) -for source in [pathlib.Path(__file__), pathlib.Path(__file__).with_name("main.rs"), - pathlib.Path(__file__).with_name("stack_queue.rs"), - pathlib.Path(__file__).with_name("lifecycle.rs"), - pathlib.Path(__file__).with_name("memcard.rs"), - pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMemcardTest.java"), - pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mem/main.pbs"), - pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java"), - pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java"), - pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java"), - pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/main.pbs")]: - print("sha256", source, hashlib.sha256(source.read_bytes()).hexdigest(), flush=True) -print("studio", subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), flush=True) -print("runtime", subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip(), flush=True) -print("runtime working tree", subprocess.check_output(["git","-C",str(runtime),"status","--short"],text=True).strip() or "clean",flush=True) -for source in [pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java"), - pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java"), - pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs"), - runtime / "crates/console/prometeu-vm/src/virtual_machine/array_copy.rs"]: - print("sha256",source,hashlib.sha256(source.read_bytes()).hexdigest(),flush=True) -print("platform", platform.platform(), "limits=default", "capabilities=MEMCARD" if args.memcard_only else "capabilities=NONE", flush=True) -print("profile", "release" if args.release else "dev", "features=resource-diagnostics", flush=True) -for relative in ["Cargo.lock", "docs/vm-arch/INTRINSICS.csv", "docs/vm-arch/BUILTIN_CONSTANTS.csv", "crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv", "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv"]: - print("sha256", relative, hashlib.sha256((runtime / relative).read_bytes()).hexdigest(), flush=True) -with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory: - root = pathlib.Path(directory) - manifest = '[package]\nname="studio-pbx-conformance"\nversion="0.1.0"\nedition="2024"\n[dependencies]\n' - for crate in ["prometeu-bytecode", "prometeu-hal", "prometeu-vm", "prometeu-system", "prometeu-firmware", "prometeu-drivers"]: - features = ',features=["resource-diagnostics"]' if crate == "prometeu-vm" else '' - manifest += f'{crate}={{path={json.dumps(str(runtime / "crates/console" / crate))}{features}}}\n' - manifest += 'serde_json="1.0.149"\njsonschema={version="0.33",default-features=false}\n' - (root / "Cargo.toml").write_text(manifest) - (root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text()) - (root / "src").mkdir() - (root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text()) - (root / "src/stack_queue.rs").write_text(pathlib.Path(__file__).with_name("stack_queue.rs").read_text()) - (root / "src/animation.rs").write_text(pathlib.Path(__file__).with_name("animation.rs").read_text()) - (root / "src/result.rs").write_text(pathlib.Path(__file__).with_name("result.rs").read_text()) - (root / "src/memcard.rs").write_text(pathlib.Path(__file__).with_name("memcard.rs").read_text()) - (root / "src/lifecycle.rs").write_text(pathlib.Path(__file__).with_name("lifecycle.rs").read_text()) - subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--animation-only"] if args.animation_only else []), *(["--result-only"] if args.result_only else []), *(["--memcard-only"] if args.memcard_only else []), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True) diff --git a/tools/pbx-conformance/stack_queue.rs b/tools/pbx-conformance/stack_queue.rs deleted file mode 100644 index ac11192e..00000000 --- a/tools/pbx-conformance/stack_queue.rs +++ /dev/null @@ -1,570 +0,0 @@ -//! Real PBS Stack/Queue qualification against the unchanged production provider. -use super::*; -use prometeu_bytecode::{TRAP_RESOURCE_LIMIT, decode_next, isa::core::CoreOpCode as Op}; -use prometeu_vm::{ - LogicalFrameEndingReason as End, - resource_budget::{RuntimeLimits, RuntimeResource as Q}, - resource_diagnostics::{StorageObject, StorageValue as V}, -}; - -fn load( - root: &std::path::Path, - collection: &str, - name: &str, - suffix: &str, -) -> std::sync::Arc { - let path = root.join(format!("pbs-{collection}-{name}{suffix}.pbx")); - let bytes = - std::fs::read(&path).unwrap_or_else(|e| panic!("mandatory {}: {e}", path.display())); - ValidatedProgramImage::load( - &bytes, - &mut LoadBudget::new(LoadLimits::default()), - caps::NONE, - ) - .unwrap_or_else(|e| panic!("{}: {e:?}", path.display())) -} -fn state( - vm: &VirtualMachine, - image: &ValidatedProgramImage, - collection: &str, -) -> Vec { - let objects = vm.heap().diagnostic_typed_storage(); - let name = format!("{collection}"); - let owner = objects - .iter() - .find(|o| { - image.registry().declarations().types[o.type_id.0 as usize] - .name - .as_deref() - == Some(&name) - }) - .expect("owner") - .clone(); - let V::Reference(storage) = owner.groups[0][0] else { - panic!("backing reference") - }; - let backing = objects - .iter() - .find(|o| o.reference == storage) - .expect("backing") - .clone(); - vec![owner, backing] -} -fn integer(group: &[V]) -> i64 { - let [V::Int64(value)] = group else { - panic!("long field {group:?}") - }; - *value -} -fn validate( - vm: &VirtualMachine, - image: &ValidatedProgramImage, - collection: &str, - expected: &[i32], - capacity: usize, - start: usize, -) { - let objects = state(vm, image, collection); - let owner = &objects[0]; - let backing = &objects[1]; - assert_eq!(backing.groups.len(), capacity); - assert_eq!( - integer(&owner.groups[if collection == "stack" { 1 } else { 2 }]), - expected.len() as i64 - ); - if collection == "queue" { - assert_eq!(integer(&owner.groups[1]), start as i64); - } - let mut occupied = std::collections::BTreeSet::new(); - for (offset, expected) in expected.iter().enumerate() { - let index = (start + offset) % capacity; - occupied.insert(index); - let [V::Int64(_), V::Int32(value)] = backing.groups[index].as_slice() else { - panic!("present complete int group") - }; - assert_eq!(value, expected); - } - for (index, group) in backing.groups.iter().enumerate() { - if !occupied.contains(&index) { - assert_eq!(*group, vec![V::Null, V::Null], "inactive slot {index}"); - } - } -} -fn release(vm: VirtualMachine) { - let observer = vm.resource_observer(); - drop(vm); - for q in [ - Q::GuestBytes, - Q::HandleSlots, - Q::AuxiliaryBytes, - Q::TemporaryBytes, - Q::StringBytes, - Q::StringAllocations, - ] { - assert_eq!(observer.used(q), 0, "last owner release {q:?}"); - } -} -pub(super) fn verify(root: &std::path::Path) { - let successes = [ - "basic", - "capacity", - "arithmetic", - "cursor-empty", - "cursor-single", - "snapshot", - "cursor-order", - "groups", - "references", - "native", - "evaluation", - ]; - let mut cases = 0; - for collection in ["stack", "queue"] { - for (name, fault) in successes - .into_iter() - .map(|n| (n, None)) - .chain( - ["fault-negative", "fault-too-large", "fault-required"] - .into_iter() - .map(|n| (n, Some(prometeu_bytecode::TRAP_EXPLICIT))), - ) - .chain((collection == "queue").then_some(("wrap", None))) - { - for suffix in ["", "-optimized"] { - let image = load(root, collection, name, suffix); - let mut vm = VirtualMachine::from_image(image, Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm - .run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - if let Some(expected) = fault { - let End::Trap(info) = report.reason else { - panic!("{collection}/{name}{suffix}: {report:?}") - }; - assert_eq!(info.code, expected); - } else { - assert!( - matches!(report.reason, End::Halted | End::EndOfRom), - "{collection}/{name}{suffix}: {report:?}" - ); - assert_eq!( - vm.operand_stack_top(1), - vec![Value::Int32(42)], - "{collection}/{name}{suffix}" - ); - } - release(vm); - cases += 1; - println!("STACK QUEUE SOURCE PASS {collection}/{name}{suffix}"); - } - } - refusals(root, collection); - postwrite_probe(root, collection); - gc(root, collection); - } - distribution(root); - println!("STACK QUEUE MANDATORY BEHAVIOR CASES {cases}"); -} -fn marker(image: &ValidatedProgramImage, value: i32) -> usize { - let mut pc = 0; - let mut found = Vec::new(); - while pc < image.code().len() { - let i = decode_next(pc, image.code()).unwrap(); - if i.opcode == Op::PushI32 && i.imm_i32().unwrap() == value { - found.push(pc); - } - pc = i.next_pc; - } - assert_eq!(found.len(), 1); - found[0] -} -fn refusals(root: &std::path::Path, collection: &str) { - let mut total = 0; - let mut after_writes = 0; - let mut backing_refusal = false; - let mut snapshot_refusal = false; - for name in [ - "insert", "growth", "zero", "remove", "clear", "peek", "cursor", "empty", - ] - .into_iter() - .chain((collection == "queue").then_some("wrapped")) - { - for suffix in ["", "-optimized"] { - let image = load(root, collection, &format!("refusal-{name}"), suffix); - let before_pc = marker(&image, 314160); - let after_pc = marker(&image, 314161); - let prepare = |limits| { - let mut vm = VirtualMachine::from_image(image.clone(), limits); - vm.prepare_boot_call().unwrap(); - vm.insert_breakpoint(before_pc); - vm.insert_breakpoint(after_pc); - vm - }; - let mut baseline = prepare(RuntimeLimits::default()); - assert!(matches!( - baseline - .run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None)) - .unwrap() - .reason, - End::Breakpoint - )); - let initial: Vec = if name == "zero" || name == "empty" { - vec![] - } else if name == "wrapped" { - vec![2, 3, 4, 5] - } else { - vec![0, 1, 2, 3] - }; - let old_capacity = if name == "zero" || name == "empty" { - 0 - } else if name == "growth" || name == "wrapped" { - 4 - } else { - 8 - }; - validate( - &baseline, - &image, - collection, - &initial, - old_capacity, - if name == "wrapped" { 2 } else { 0 }, - ); - let old = state(&baseline, &image, collection); - let before = baseline.resource_snapshot(); - baseline.remove_breakpoint(before_pc); - let mut successful = Vec::new(); - let mut max_arrays = 0; - loop { - max_arrays = max_arrays.max( - baseline - .heap() - .diagnostic_typed_storage() - .iter() - .filter(|o| { - matches!( - image.registry().declarations().types[o.type_id.0 as usize].kind, - prometeu_bytecode::registry::TypeKind::Array(_) - ) - }) - .count(), - ); - successful.push((baseline.pc(), observe_originals(&baseline, &old))); - let report = baseline - .run_budget(1, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - if baseline.pc() == after_pc { - break; - } - assert!( - matches!(report.reason, End::BudgetExhausted), - "{collection}/{name}: {report:?}" - ); - assert!(successful.len() < 200_000); - } - let after = baseline.resource_snapshot(); - let mut expected = initial.clone(); - match name { - "insert" | "growth" | "zero" | "wrapped" => expected.push(42), - "remove" => { - if collection == "stack" { - expected.pop(); - } else { - expected.remove(0); - } - } - "clear" => expected.clear(), - _ => (), - } - let capacity = match name { - "zero" => 1, - "growth" | "wrapped" => 6, - _ => old_capacity, - }; - validate( - &baseline, - &image, - collection, - &expected, - capacity, - if collection == "queue" && name == "remove" { - 1 - } else { - 0 - }, - ); - if ["growth", "zero", "wrapped"].contains(&name) { - assert!(max_arrays >= 2, "old/candidate coexistence"); - } else { - assert_eq!( - max_arrays, 1, - "ordinary update/capture never reconstructs backing" - ); - } - if ["peek", "cursor", "empty"].contains(&name) { - assert_eq!(state(&baseline, &image, collection), old); - } - println!( - "STACK QUEUE PEAK {collection}/{name}{suffix} arrays={max_arrays} before={:?} after={:?}", - before.budget.peaks, after.budget.peaks - ); - let mut count = 0; - let mut partial = 0; - for q in [ - Q::GuestBytes, - Q::HandleSlots, - Q::AuxiliaryBytes, - Q::TemporaryBytes, - Q::CallDepth, - ] { - let lower = before.budget.peaks[q as usize]; - let upper = after.budget.peaks[q as usize]; - if lower >= upper { - continue; - } - let mut limits = vec![lower, lower + (upper - lower) / 2, upper - 1]; - if q == Q::HandleSlots { - limits.extend(lower..upper.min(lower + 24)); - } - limits.sort_unstable(); - limits.dedup(); - for limit in limits { - let mut vm = prepare(RuntimeLimits::default().lowered(q, limit).unwrap()); - assert!( - matches!( - vm.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None)) - .unwrap() - .reason, - End::Breakpoint - ), - "{collection}/{name}/{q:?}={limit} setup" - ); - let original = state(&vm, &image, collection); - vm.remove_breakpoint(before_pc); - let (report, prefix, mutated) = - trace_collection_attempt(&mut vm, &original, after_pc); - assert_mutation_prefix(&prefix, &successful); - if let End::Trap(info) = report.reason { - assert_eq!(info.code, TRAP_RESOURCE_LIMIT); - let current = observe_originals(&vm, &original); - if !mutated { - assert_eq!( - current, original, - "before first write preserves full original state" - ); - } - if ["peek", "cursor", "empty"].contains(&name) { - assert_eq!(current, original); - } - let instruction = decode_next(info.pc as usize, image.code()).unwrap(); - backing_refusal |= instruction.opcode == Op::ArrayNew; - if instruction.opcode == Op::StructNew { - snapshot_refusal |= image.registry().declarations().types - [instruction.imm_u32().unwrap() as usize] - .name - .as_deref() - == Some("_SnapshotNode"); - } - count += 1; - partial += usize::from(mutated); - println!( - "STACK QUEUE REFUSAL {collection}/{name}{suffix} mutated={mutated} resource={q:?} limit={limit} opcode={:?}", - instruction.opcode - ); - } else { - assert!( - matches!(report.reason, End::BudgetExhausted | End::Breakpoint) - && vm.pc() == after_pc - ); - } - release(vm); - } - } - assert!( - count > 0, - "{collection}/{name}: operation-specific natural refusal required" - ); - total += count; - after_writes += partial; - println!( - "STACK QUEUE PHASE SUMMARY {collection}/{name}{suffix} refusals={count} after_write={partial}" - ); - } - } - assert!( - backing_refusal && snapshot_refusal, - "backing and snapshot preparation refusals required" - ); - println!("STACK QUEUE NATURAL REFUSALS {collection} total={total} after_write={after_writes}"); -} -fn postwrite_probe(root: &std::path::Path, collection: &str) { - // Separate test-only instrumentation: not natural failure frequency evidence. - for suffix in ["", "-optimized"] { - let image = load(root, collection, "injected-growth", suffix); - let mut vm = VirtualMachine::from_image( - image.clone(), - RuntimeLimits::default() - .lowered(Q::GuestBytes, 500_000) - .unwrap(), - ); - vm.prepare_boot_call().unwrap(); - let mut found = false; - for _ in 0..100_000 { - let instruction = decode_next(vm.pc(), image.code()).unwrap(); - if instruction.opcode == Op::ArrayNew - && vm.operand_stack_top(1) == vec![Value::Int64(1_000_000)] - { - let original = vm.heap().diagnostic_typed_storage(); - let objects = state(&vm, &image, collection); - assert_eq!( - integer(&objects[0].groups[if collection == "stack" { 1 } else { 2 }]), - 2 - ); - assert_eq!(objects[1].groups.len(), 3); - assert!(matches!( - objects[1].groups[2].as_slice(), - [V::Int64(_), V::Int32(42)] - )); - let operands = vm.operand_stack_top(1).to_vec(); - let report = vm - .run_budget(1, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - let End::Trap(info) = report.reason else { - panic!("post-write probe: {report:?}") - }; - assert_eq!(info.code, TRAP_RESOURCE_LIMIT); - assert_eq!(vm.heap().diagnostic_typed_storage(), original); - assert_eq!(vm.operand_stack_top(1), operands); - println!( - "STACK QUEUE TEST-ONLY POST-WRITE PASS {collection}{suffix}: backing=3 old size=2 appended=42 retained" - ); - found = true; - break; - } - let report = vm - .run_budget(1, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - assert!(matches!(report.reason, End::BudgetExhausted)); - } - assert!(found); - release(vm); - } -} -fn gc(root: &std::path::Path, collection: &str) { - for suffix in ["", "-optimized"] { - for (name, counts) in [ - ("gc-snapshot", vec![1200, 1, 1, 0]), - ("gc-collection", vec![64, 61, 0, 1, 0]), - ] { - let image = load(root, collection, name, suffix); - let mut vm = VirtualMachine::from_image(image.clone(), Default::default()); - vm.prepare_boot_call().unwrap(); - let mut previous = 0; - for (round, count) in counts.into_iter().enumerate() { - let report = vm - .run_budget(100_000_000, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - assert!( - matches!(report.reason, End::FrameSync), - "{collection}/{name}/{round}: {report:?}" - ); - let collections = vm.resource_snapshot().gc.collections; - assert!( - collections > previous, - "actual collection, not only safepoint" - ); - previous = collections; - let objects = vm.heap().diagnostic_typed_storage(); - let named = |n: &str| { - objects - .iter() - .filter(|o| { - image.registry().declarations().types[o.type_id.0 as usize] - .name - .as_deref() - == Some(n) - }) - .count() - }; - assert_eq!( - named("Item"), - count, - "{collection}/{name}/{round}: payload roots" - ); - let arrays = objects - .iter() - .filter(|o| { - matches!( - image.registry().declarations().types[o.type_id.0 as usize].kind, - prometeu_bytecode::registry::TypeKind::Array(_) - ) - }) - .count(); - if name == "gc-snapshot" { - assert_eq!(named("_SnapshotNode"), count); - assert_eq!(arrays, 0, "snapshot retains no source backing"); - } else { - assert_eq!( - arrays, - usize::from(round < 4), - "only retained backing, no replaced arrays" - ); - assert_eq!(named("_SnapshotNode"), 0); - } - println!( - "STACK QUEUE GC PASS {collection}/{name}{suffix} round={round} items={count} arrays={arrays}" - ); - } - let report = vm - .run_budget(100_000, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - assert!(matches!(report.reason, End::Halted | End::EndOfRom)); - assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)]); - release(vm); - } - } -} -fn distribution(root: &std::path::Path) { - for name in ["imports", "installed"] { - let image = load(root, "stack-queue", name, ""); - let mut vm = VirtualMachine::from_image(image.clone(), Default::default()); - vm.prepare_boot_call().unwrap(); - let report = vm - .run_budget(2_000_000, &mut NoNative, &mut HostContext::new(None)) - .unwrap(); - assert!( - matches!(report.reason, End::FrameSync | End::Halted | End::EndOfRom), - "{name}: {report:?}" - ); - let objects = vm.heap().diagnostic_typed_storage(); - let get = |reference| objects.iter().find(|o| o.reference == reference).unwrap(); - let mut lasts = Vec::new(); - for cursor in objects.iter().filter(|o| { - image.registry().declarations().types[o.type_id.0 as usize] - .name - .as_deref() - == Some("_SnapshotCursor") - }) { - let V::Reference(carrier) = cursor.groups[0][0] else { - panic!("current carrier") - }; - let V::Reference(node) = get(carrier).groups[0][0] else { - panic!("node") - }; - let node = get(node); - assert_eq!(node.groups[1], vec![V::Null], "completed traversal"); - let V::Int32(value) = node.groups[0][0] else { - panic!("value") - }; - lasts.push(value); - } - lasts.sort_unstable(); - assert_eq!( - lasts, - vec![20, 22], - "both order-sensitive snapshots traversed" - ); - release(vm); - println!("STACK QUEUE DISTRIBUTION PASS {name}"); - } -} diff --git a/tools/runtime-catalog/verify.py b/tools/runtime-catalog/verify.py deleted file mode 100644 index cb394e21..00000000 --- a/tools/runtime-catalog/verify.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Explicit provider check; ordinary Studio compilation does not invoke this tool.""" -import argparse -import hashlib -import pathlib -import platform -import subprocess -import tempfile - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--runtime", type=pathlib.Path, required=True) - args = parser.parse_args() - studio = pathlib.Path(__file__).resolve().parents[2] - mirror = studio / "docs/vm-arch" - properties = dict(line.split("=", 1) for line in - (mirror / "runtime-catalog.properties").read_text().splitlines() if line) - runtime = args.runtime.resolve(strict=True) - revision = subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip() - if revision != properties["runtime.revision"]: - raise SystemExit(f"Expected selected provider {properties['runtime.revision']}, found {revision}; " - "this is an evidence-target mismatch, not a runtime compatibility verdict") - # Evidence must correspond to committed source, not just two matching local copies. - dirty = subprocess.check_output(["git", "-C", str(runtime), "status", "--porcelain"], text=True) - if dirty: - raise SystemExit("Provider checkout is dirty; verify the selected revision in a clean checkout") - for name in ("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv"): - committed = subprocess.check_output(["git", "-C", str(runtime), "show", f"{revision}:docs/vm-arch/{name}"]) - if committed != (runtime / "docs/vm-arch" / name).read_bytes() or committed != (mirror / name).read_bytes(): - raise SystemExit(f"Provider/mirror bytes differ: {name}") - digest = hashlib.sha256(committed).hexdigest() - if digest != properties[name + ".sha256"]: - raise SystemExit(f"Provenance hash mismatch: {name}") - print(f"MATCH {name} sha256={digest}", flush=True) - print(f"Provider {revision}; {platform.platform()}; Cargo test profile, default features", flush=True) - with tempfile.TemporaryDirectory(prefix="studio-catalog-provider-") as target: - subprocess.run(["cargo", "test", "--locked", "--offline", "--target-dir", target, - "-p", "prometeu-vm", "--test", "numeric_contract", - "exported_artifacts_match_the_single_runtime_catalog", "--", "--exact"], - cwd=runtime, check=True) - - -if __name__ == "__main__": - main()