feat(pbs): add sprite animation and shared Studio authoring

Implement DEC-0084 with factory-only Sprite/Animator structs, complete result
lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP
authoring through shared services.

Qualify native dev/release with ordinary and optimized producers, zero-allocation
playback, private-cycle reclamation, canonical Composer pixels, installed JARs
and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
This commit is contained in:
2026-11-05 15:16:07 +00:00
parent 1d8b8c2101
commit bf31184d4d
151 changed files with 4823 additions and 98 deletions
+14 -1
View File
@@ -63,7 +63,7 @@ javafx {
}
// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests.
tasks.named<Test>("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") }
tasks.named<Test>("test") { exclude("**/AnimationDesktopTest.class", "**/AnimationInstalledRuntimeTest.class", "**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") }
tasks.register<Test>("devDesktopTest") {
group = "verification"
description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)."
@@ -74,6 +74,16 @@ tasks.register<Test>("devDesktopTest") {
systemProperty("java.awt.headless", "false")
}
tasks.register<Test>("animationDesktopTest") {
group = "verification"
description = "Authors and repairs an animation through the actual JavaFX editor (requires a display)."
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform()
include("**/AnimationDesktopTest.class")
systemProperty("java.awt.headless", "false")
}
tasks.register<Test>("installedKnowledgeTest") {
group = "verification"
description = "Reads installed references and compiles their example in an isolated JVM outside the checkout."
@@ -96,6 +106,9 @@ tasks.register<Test>("headlessProcessTest") {
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform()
include("**/HeadlessInstalledRuntimeTest.class")
include("**/AnimationInstalledRuntimeTest.class")
systemProperty("pbs.registryConformanceDirectory",
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(""))
}
@@ -171,8 +171,28 @@ public class StudioApplicationConfiguration {
}
@Bean
CompilerBuildGateway compilerBuildGateway() {
return new CompilerBuildGatewayAdapter();
p.animation.GlyphBankLayoutSource glyphBankLayoutSource(PackerWorkspaceService packer,ObjectMapper mapper) {
return new p.studio.app.assets.PackerGlyphBankLayouts(packer,mapper);
}
@Bean
p.studio.core.assets.animation.DefaultAnimationService animationEngine(p.animation.GlyphBankLayoutSource layouts,AssetCatalog catalog) {
return new p.studio.core.assets.animation.DefaultAnimationService(layouts,catalog);
}
@Bean
p.studio.api.assets.animation.AnimationService animationService(p.studio.core.assets.animation.DefaultAnimationService engine,p.studio.api.automation.ProjectAccess access) {
return new p.studio.core.assets.animation.ManualAnimationService(engine,access);
}
@Bean
p.studio.api.assets.animation.AnimationTasks animationTasks(p.studio.core.project.ProjectAccessRegistry projects,ProjectCatalog catalog,p.studio.core.assets.animation.DefaultAnimationService engine) {
return new p.studio.core.session.TaskAnimationService(projects,catalog,engine);
}
@Bean
CompilerBuildGateway compilerBuildGateway(p.animation.GlyphBankLayoutSource layouts) {
return new CompilerBuildGatewayAdapter(layouts);
}
@Bean
@@ -213,8 +233,8 @@ public class StudioApplicationConfiguration {
}
@Bean
LspServerLifecycle lspServerLifecycle() {
return new LspServerLifecycleImpl();
LspServerLifecycle lspServerLifecycle(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events) {
return new LspServerLifecycleImpl(layouts,(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer)));
}
@Bean
@@ -284,13 +304,15 @@ public class StudioApplicationConfiguration {
TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) {
return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, p.studio.api.assets.animation.AnimationService animationService) {
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, connectionGuide);
factory.setAnimationService(animationService);
return factory;
}
@Bean
@@ -300,8 +322,8 @@ public class StudioApplicationConfiguration {
@Bean
p.studio.api.automation.ProjectKnowledge projectKnowledge(
p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper) {
return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper);
p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper, p.animation.GlyphBankLayoutSource layouts) {
return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper, layouts);
}
@Bean
@@ -331,10 +353,11 @@ public class StudioApplicationConfiguration {
@Bean
p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper,
p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language,
p.studio.api.automation.TaskTools tasks, java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
p.studio.api.automation.TaskTools tasks, p.studio.api.assets.animation.AnimationTasks animations, java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
var handlers = new java.util.LinkedHashMap<>(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper));
handlers.putAll(p.studio.app.mcp.McpLanguageTools.handlers(language, mapper));
handlers.putAll(p.studio.app.mcp.McpTaskTools.handlers(tasks, mapper, headless.isPresent()));
handlers.putAll(p.studio.app.mcp.McpAnimationTools.handlers(animations, mapper));
return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers);
}
@@ -58,6 +58,9 @@ public final class StudioUiFactory {
private final ProjectActivityHistoryStore activityHistoryStore;
private final p.studio.api.automation.AgentConnectionGuide connectionGuide;
private p.studio.api.assets.animation.AnimationService animationService;
public void setAnimationService(p.studio.api.assets.animation.AnimationService service){this.animationService=service;}
public StudioUiFactory(
ProjectCatalog projectCatalog,
KnownProjects knownProjects,
@@ -113,11 +116,13 @@ public final class StudioUiFactory {
}
public StudioWindowCoordinator create(Stage stage) {
return new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
var coordinator = new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, executor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, connectionGuide);
if(animationService!=null)coordinator.setAnimationService(animationService);
return coordinator;
}
}
@@ -0,0 +1,22 @@
package p.studio.app.assets;
import p.animation.*;
import p.packer.PackerWorkspaceService;
import p.packer.messages.*;
import java.nio.file.Path;
import java.util.UUID;
import java.util.function.Function;
import com.fasterxml.jackson.databind.ObjectMapper;
/** Only application composition knows the public Packer adapter. */
public final class PackerGlyphBankLayouts implements GlyphBankLayoutSource {
private final PackerWorkspaceService packer;private final ObjectMapper mapper;
public PackerGlyphBankLayouts(PackerWorkspaceService packer,ObjectMapper mapper){this.packer=packer;this.mapper=mapper;}
private GetGlyphBankLayoutRequest request(Path root,UUID uuid){
try{return new GetGlyphBankLayoutRequest(new PackerProjectContext(mapper.readTree(root.resolve("prometeu.json").toFile()).path("name").asText(),root),uuid);}
catch(java.io.IOException e){throw new IllegalArgumentException("Cannot read project identity",e);}
}
private static GlyphBankLayout map(p.packer.dtos.PackerGlyphBankLayoutDTO bank){
return new GlyphBankLayout(bank.assetUuid(),bank.revision(),bank.assetRoot(),bank.glyphs().stream().map(g->new GlyphBankLayout.Glyph(g.artifactId(),g.glyphId(),g.fingerprint(),g.imagePath(),g.width(),g.height(),g.indices())).toList(),bank.rgbaPalettes());
}
@Override public GlyphBankLayout resolve(Path root,UUID uuid){return map(packer.getGlyphBankLayout(request(root,uuid)));}
@Override public <T> T withLayout(Path root,UUID uuid,Function<GlyphBankLayout,T> work){return packer.withGlyphBankLayout(request(root,uuid),bank->work.apply(map(bank)));}
}
@@ -11,11 +11,15 @@ import java.util.LinkedHashSet;
import java.util.function.Consumer;
public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway {
private final p.animation.GlyphBankLayoutSource layouts;
public CompilerBuildGatewayAdapter(){this(null);}
public CompilerBuildGatewayAdapter(p.animation.GlyphBankLayoutSource layouts){this.layouts=layouts;}
@Override
public CompilerBuildOutput compile(ProjectReference project, Consumer<String> logSink) {
final var config = new BuilderPipelineConfig(false, project.rootPath().toString());
var context=BuilderPipelineContext.fromConfig(config);context.glyphBankLayoutSource=layouts;
final var result = BuilderPipelineService.INSTANCE.build(
BuilderPipelineContext.fromConfig(config),
context,
LogAggregator.with(logSink));
final var capabilities = new LinkedHashSet<>(
result.compileResult().analysisSnapshot().irBackend()
@@ -26,9 +26,13 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge {
private final ProjectAccessRegistry openProjects;
private final ProjectCatalog projects;
private final ObjectMapper mapper;
private final CompilerLanguageServiceBridge languageBridge = new CompilerLanguageServiceBridge();
private final CompilerLanguageServiceBridge languageBridge;
public CompilerProjectKnowledge(ProjectAccessRegistry openProjects, ProjectCatalog projects, ObjectMapper mapper) {
this(openProjects,projects,mapper,null);
}
public CompilerProjectKnowledge(ProjectAccessRegistry openProjects,ProjectCatalog projects,ObjectMapper mapper,p.animation.GlyphBankLayoutSource layouts) {
this.languageBridge=new CompilerLanguageServiceBridge(layouts);
this.openProjects = Objects.requireNonNull(openProjects);
this.projects = Objects.requireNonNull(projects);
this.mapper = Objects.requireNonNull(mapper);
@@ -18,6 +18,7 @@ final class ContractSchema {
if (schema.has("const") && !schema.get("const").equals(value)) fail();
if (schema.has("type")) {
boolean valid = switch (schema.get("type").asText()) {
case "null" -> value.isNull();
case "object" -> value.isObject();
case "array" -> value.isArray();
case "string" -> value.isTextual();
@@ -27,6 +28,8 @@ final class ContractSchema {
};
if (!valid) fail();
}
if(schema.has("pattern")&&!value.textValue().matches(schema.get("pattern").textValue()))fail();
if(schema.has("minItems")&&value.size()<schema.get("minItems").intValue())fail();
if (schema.has("minLength") && value.textValue().codePointCount(0, value.textValue().length()) < schema.get("minLength").intValue()) fail();
if (schema.has("minimum") && value.longValue() < schema.get("minimum").longValue()) fail();
if (schema.has("maximum") && value.longValue() > schema.get("maximum").longValue()) fail();
@@ -0,0 +1,39 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import p.animation.AnimationCodec;
import p.studio.api.assets.animation.*;
import p.studio.api.automation.*;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
/** Wire adaptation only; UI and AI call the same shared application service. */
public final class McpAnimationTools {
private McpAnimationTools(){}
public static Map<String,Function<JsonNode,McpToolResult>> handlers(AnimationTasks tasks,ObjectMapper mapper){
return Map.of("studio_animation_query",args->call(tasks,mapper,args),"studio_animation_update",args->call(tasks,mapper,args));
}
private static McpToolResult call(AnimationTasks tasks,ObjectMapper mapper,JsonNode args){
try {
var response=tasks.execute(Path.of(args.required("projectRoot").textValue()),args.required("taskId").textValue(),project->new AnimationService.Request(
AnimationService.Operation.valueOf(args.required("operation").textValue().toUpperCase(Locale.ROOT)),project,
args.has("assetUuid")?UUID.fromString(args.get("assetUuid").textValue()):null,
text(args,"animatorId"),text(args,"clipName"),args.has("elapsedTicks")?args.get("elapsedTicks").longValue():null,
args.has("paletteId")?args.get("paletteId").intValue():null,text(args,"expectedRevision"),
args.has("document")?new AnimationCodec().decode(args.get("document").toString()):null,text(args,"proposalHash"),text(args,"expectedBankRevision")));
ObjectNode value=mapper.valueToTree(response);
canonicalView(mapper,value.get("view"));if(value.path("definitions").isArray())for(var view:value.get("definitions"))canonicalView(mapper,view);
if(response.proposal()!=null)((ObjectNode)value.get("proposal")).set("document",mapper.readTree(new AnimationCodec().encode(response.proposal().document())));
if(response.preview()!=null)((ObjectNode)value.get("preview")).remove("image");
return McpToolResult.successWithCapture(mapper,value,response.preview()==null?null:response.preview().image(),false);
}catch(ControlDeniedException|AutomationException authority){throw authority;}
catch(IllegalArgumentException invalid){return McpToolResult.failure(mapper,new AutomationFailure(AutomationFailure.Code.ANIMATION_INVALID,invalid.getMessage()));}
catch(IllegalStateException conflict){return McpToolResult.failure(mapper,new AutomationFailure(conflict.getMessage()!=null&&conflict.getMessage().contains("conflict")?AutomationFailure.Code.ANIMATION_CONFLICT:AutomationFailure.Code.INFRASTRUCTURE_FAILURE,conflict.getMessage()));}
catch(java.io.IOException failure){throw new IllegalStateException("Cannot encode animation response",failure);}
}
private static String text(JsonNode node,String field){return node.hasNonNull(field)?node.get(field).textValue():null;}
private static void canonicalView(ObjectMapper mapper,JsonNode view)throws java.io.IOException{
if(view!=null&&view.isObject()&&view.hasNonNull("document"))((ObjectNode)view).set("document",mapper.readTree(view.required("json").asText()));
}
}
@@ -2378,6 +2378,945 @@
"exampleValue": {
"sessionId": "runtime-example"
}
},
{
"name": "studio_animation_query",
"authority": "task",
"description": "List, get, validate or preview canonical bank animation definitions through the same services as the Assets editor. Preview uses explicit ticks and transient palette input; reads never rebind.",
"inputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "list"
},
"assetUuid": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "get"
},
"assetUuid": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "validate"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "preview"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"animatorId": {
"type": "string",
"minLength": 1
},
"clipName": {
"type": "string",
"minLength": 1
},
"elapsedTicks": {
"type": "integer",
"minimum": 0
},
"paletteId": {
"type": "integer",
"minimum": 0,
"maximum": 63
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"animatorId",
"clipName",
"elapsedTicks",
"paletteId"
],
"additionalProperties": false
}
],
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation"
]
},
"outputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"status": {
"const": "ok"
},
"value": {
"type": "object"
}
},
"required": [
"status",
"value"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"status": {
"const": "error"
},
"error": {
"type": "object",
"properties": {
"code": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string"
},
"runtimeError": {
"type": "object",
"additionalProperties": true
}
},
"required": [
"code",
"message"
],
"additionalProperties": false
}
},
"required": [
"status",
"error"
],
"additionalProperties": false
}
]
},
"annotations": {
"readOnlyHint": true,
"openWorldHint": false
},
"exampleArguments": {
"projectRoot": "/projects/game",
"taskId": "task-example",
"operation": "get",
"assetUuid": "12345678-1234-1234-1234-123456789abc"
},
"exampleValue": {
"definitions": [],
"diagnostics": []
}
},
{
"name": "studio_animation_update",
"authority": "task",
"description": "Save/delete animator definitions or prepare/apply an explicit binding-only rebind. Expected revisions prevent overwrites; only create accepts explicitly null expectedRevision. No arbitrary file paths or extra approval flow.",
"inputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "save"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"oneOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision",
"document"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "delete"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"type": "string",
"minLength": 1
},
"animatorId": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision",
"animatorId"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "prepare_rebind"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "apply_rebind"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"type": "string",
"minLength": 1
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
},
"proposalHash": {
"type": "string",
"minLength": 1
},
"expectedBankRevision": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision",
"document",
"proposalHash",
"expectedBankRevision"
],
"additionalProperties": false
}
],
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation"
]
},
"outputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"status": {
"const": "ok"
},
"value": {
"type": "object"
}
},
"required": [
"status",
"value"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"status": {
"const": "error"
},
"error": {
"type": "object",
"properties": {
"code": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string"
},
"runtimeError": {
"type": "object",
"additionalProperties": true
}
},
"required": [
"code",
"message"
],
"additionalProperties": false
}
},
"required": [
"status",
"error"
],
"additionalProperties": false
}
]
},
"annotations": {
"readOnlyHint": false,
"openWorldHint": false
},
"exampleArguments": {
"projectRoot": "/projects/game",
"taskId": "task-example",
"operation": "save",
"assetUuid": "12345678-1234-1234-1234-123456789abc",
"expectedRevision": null,
"document": {
"schema_version": 1,
"bank_asset_uuid": "12345678-1234-1234-1234-123456789abc",
"bindings": [],
"animators": []
}
},
"exampleValue": {
"definitions": [],
"diagnostics": []
}
}
]
}
@@ -30,7 +30,7 @@ class StudioApplicationConfigurationTest {
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
org.junit.jupiter.api.Assertions.assertEquals(22, tools.size());
org.junit.jupiter.api.Assertions.assertEquals(24, tools.size());
assertTrue(context.getBean(p.studio.core.runtime.HeadlessGateway.class) instanceof p.studio.app.runtime.HeadlessProcessGateway);
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
@@ -0,0 +1,54 @@
package p.studio.app.animation;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl;
import p.animation.*;
import java.nio.file.*;
import java.util.concurrent.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
/** Actual JavaFX editing, shared save/preview, drift repair and handoff lifecycle. */
class AnimationDesktopTest {
@TempDir Path root;
@BeforeAll static void toolkit()throws Exception{
var ready=new CompletableFuture<Void>();
try{Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});}
catch(IllegalStateException running){ready.complete(null);}
ready.get(10,TimeUnit.SECONDS);
}
@AfterAll static void stopToolkit(){Platform.exit();}
static <T>T fx(Supplier<T> work)throws Exception{var result=new CompletableFuture<T>();Platform.runLater(()->{try{result.complete(work.get());}catch(Throwable f){result.completeExceptionally(f);}});return result.get(10,TimeUnit.SECONDS);}
static void await(BooleanSupplier test)throws Exception{long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);while(!test.getAsBoolean()){if(System.nanoTime()>end)fail("Animation editor did not finish");Thread.sleep(10);}}
static Button button(AnimationEditorControl editor,String text){return editor.lookupAll(".button").stream().filter(n->n instanceof Button b&&b.getText().equals(text)).map(n->(Button)n).findFirst().orElseThrow();}
@Test void authorsPreviewsSavesRepairsAndCloses()throws Exception{
var fixture=new AnimationIntegrationTest();fixture.root=root;fixture.setup();
var pool=Executors.newCachedThreadPool();var stage=new Stage[1];var editor=new AnimationEditorControl[1];
try{
fx(()->{editor[0]=new AnimationEditorControl(fixture.project,fixture.manual,pool);var scroll=new ScrollPane(editor[0]);scroll.setFitToWidth(true);stage[0]=new Stage();stage[0].setTitle("Animation authoring acceptance");stage[0].setScene(new Scene(scroll,1040,940));stage[0].show();editor[0].bind(fixture.uuid);return null;});
await(()->{try{return fx(()->((Label)editor[0].lookup("#animation-status")).getText().equals("New definition"));}catch(Exception e){throw new RuntimeException(e);}});
fx(()->{((TextField)editor[0].lookup("#animation-id")).setText("hero");button(editor[0],"New animator").fire();((ComboBox<?>)editor[0].lookup("#animation-glyph")).getSelectionModel().selectFirst();((TextField)editor[0].lookup("#animation-duration")).setText("2");button(editor[0],"Add frame").fire();return null;});
assertTrue(editor[0].hasUnsavedChanges().toCompletableFuture().get());
editor[0].saveAll().toCompletableFuture().get(10,TimeUnit.SECONDS);
assertFalse(editor[0].hasUnsavedChanges().toCompletableFuture().get());
assertEquals(2,fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.get(fixture.project,fixture.uuid)).view().document().animators().getFirst().clips().getFirst().frames().getFirst().durationTicks());
fx(()->{button(editor[0],"Preview").fire();return null;});
await(()->{try{return fx(()->((ImageView)editor[0].lookup("#animation-image")).getImage()!=null);}catch(Exception e){throw new RuntimeException(e);}});
fx(()->{var snapshot=stage[0].getScene().snapshot(null);var image=new java.awt.image.BufferedImage((int)snapshot.getWidth(),(int)snapshot.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);for(int y=0;y<image.getHeight();y++)for(int x=0;x<image.getWidth();x++)image.setRGB(x,y,snapshot.getPixelReader().getArgb(x,y));try{javax.imageio.ImageIO.write(image,"png",Path.of("/tmp/dec84-animation-desktop.png").toFile());}catch(Exception e){throw new RuntimeException(e);}return null;});
var asset=(com.fasterxml.jackson.databind.node.ObjectNode)fixture.mapper.readTree(fixture.bankRoot.resolve("asset.json").toFile());((com.fasterxml.jackson.databind.node.ObjectNode)asset.path("artifacts").get(0)).put("index",1);((com.fasterxml.jackson.databind.node.ObjectNode)asset.path("artifacts").get(1)).put("index",0);fixture.mapper.writeValue(fixture.bankRoot.resolve("asset.json").toFile(),asset);
editor[0].refreshFromDisk().toCompletableFuture().get(10,TimeUnit.SECONDS);
fx(()->{button(editor[0],"Prepare rebind").fire();return null;});
await(()->{try{return fx(()->!button(editor[0],"Apply rebind").isDisabled());}catch(Exception e){throw new RuntimeException(e);}});
fx(()->{button(editor[0],"Apply rebind").fire();return null;});
await(()->fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.get(fixture.project,fixture.uuid)).view().diagnostics().isEmpty());
fx(()->{editor[0].openOrigin("/animators/0/clips/0/frames/0");editor[0].close();stage[0].close();return null;});
assertFalse(pool.isShutdown());
}finally{fx(()->{if(editor[0]!=null)editor[0].close();if(stage[0]!=null)stage[0].close();return null;});pool.shutdownNow();fixture.close();}
}
}
@@ -0,0 +1,55 @@
package p.studio.app.animation;
import java.nio.file.*;
import p.animation.*;
import p.studio.api.assets.animation.AnimationService;
import p.studio.compiler.models.BuilderPipelineContext;
import p.studio.compiler.messages.BuilderPipelineConfig;
import p.studio.compiler.workspaces.BuilderPipelineService;
import p.studio.compiler.backend.bytecode.BytecodeEmitter;
import p.studio.utilities.logs.LogAggregator;
/** Runs only with installed product JARs, outside the checkout. No runtime checkout is read. */
public final class AnimationInstalledProbe {
public static void verify(Path root,Path corpus)throws Exception{
var f=new AnimationProjectFixture();f.root=root;f.setup();
try{
f.manual.execute(AnimationService.Request.save(f.project,f.uuid,null,f.document()));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;pub fn animationProbe()->int;");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/b_"+f.uuid.toString().replace("-","")+";\n"+"""
import { AnimationError } from @core:animation;
declare global trace:int=0;
fn run()->result<AnimationError> {
let value=create_hero(3)!;let other=create_hero(3)!;
value.play("idle")!;value.advance(2)!;
if value.sprite().glyph_id!=1 || other.sprite().glyph_id!=0 {let fail=1/0;}
trace=42;return ok(());
}
[Frame]fn frame()->void {run();}
fn animationProbe()->int {return trace;}
""");
var context=BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=f.layouts;
var result=BuilderPipelineService.INSTANCE.compile(context,LogAggregator.stdout());
if(result.diagnostics().stream().anyMatch(d->d.isError()))throw new AssertionError(result.diagnostics());
Files.createDirectories(corpus);
for(boolean optimized:new boolean[]{false,true}){
var program=optimized?context.optimizedIrvm:context.irvm;
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
String prefix="pbs-animation-installed"+(optimized?"-optimized":"");Files.write(corpus.resolve(prefix+".pbx"),module.serialize());
for(int i=0;i<program.module().functions().size();i++)if(program.module().functions().get(i).name().contains("animationProbe"))Files.writeString(corpus.resolve(prefix+".probe"),Integer.toString(i));
}
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(f.layouts);
var lsp=new p.studio.lsp.messages.LspProjectContext("app","pbs",root);
for(var id:context.fileTable.identifiers()){
var path=context.fileTable.get(id).getCanonPath();if(path.startsWith(Path.of("/virtual/generated/animations"))&&path.endsWith("main.pbs")){
var source=bridge.currentSource(lsp,path).orElseThrow();
if(!source.readOnly()||source.origins().isEmpty())throw new AssertionError("Installed generated origins");
}
}
var schema=AnimationInstalledProbe.class.getClassLoader().getResource("mcp/studio-tools-v1.json");
if(schema==null||!schema.getProtocol().equals("jar"))throw new AssertionError("Installed MCP schema missing");
try(var input=schema.openStream()){String text=new String(input.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);for(var name:new String[]{"studio_animation_query","studio_animation_update"})if(!text.contains(name))throw new AssertionError(name);}
System.out.println("Installed generated animation verified: shared save, factories, read-only origins, MCP schemas, ordinary/optimized corpus");
}finally{f.close();}
}
}
@@ -0,0 +1,96 @@
package p.studio.app.animation;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.animation.*;
import p.studio.api.assets.animation.AnimationService;
import p.studio.api.project.*;
import p.studio.api.automation.*;
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
import p.studio.app.runtime.HeadlessProcessGateway;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.core.shipper.StudioShipperService;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Production packaged runtime: canonical authoring -> generated PBS -> Composer -> pixels. */
class AnimationInstalledRuntimeTest {
@TempDir Path root;
@Test void composedFramesMatchSharedPreviewAtEveryBoundary()throws Exception{
var f=new AnimationProjectFixture();f.root=root;f.setup();
var workers=Executors.newSingleThreadExecutor();
try{
f.manual.execute(AnimationService.Request.save(f.project,f.uuid,null,f.document()));
var manifest=(com.fasterxml.jackson.databind.node.ObjectNode)f.mapper.readTree(f.bankRoot.resolve("asset.json").toFile());
((com.fasterxml.jackson.databind.node.ObjectNode)manifest.path("preload")).put("enabled",true);
((com.fasterxml.jackson.databind.node.ArrayNode)manifest.path("output").path("pipeline").path("palettes"))
.addObject().put("index",1).putObject("palette").putArray("rgba8888").add(0x0000ffff).add(0xff0000ff).add(0x00ff00ff);
f.mapper.writeValue(f.bankRoot.resolve("asset.json").toFile(),manifest);
Path scene=Files.createDirectories(root.resolve("assets/scene"));
var sc=f.mapper.createObjectNode().put("schema_version",1).put("asset_uuid","22345678-1234-1234-1234-123456789abc").put("name","scene").put("type","scene_bank");
sc.putObject("preload").put("enabled",true);sc.putObject("output").put("format","SCENE/tilemap_v1").put("codec","NONE");f.mapper.writeValue(scene.resolve("asset.json").toFile(),sc);
var request=f.mapper.createObjectNode().put("schema_version",1).put("format","SCENE/tilemap_v1").put("version",1);var layers=request.putArray("layers");
for(int i=0;i<4;i++){var layer=layers.addObject().put("active",true).put("glyph_asset_id",1).put("tile_size",16).put("parallax_factor_x",1.0).put("parallax_factor_y",1.0).put("width",1).put("height",1);layer.putArray("tiles").addObject().put("active",false).put("glyph_id",0).put("palette_id",0).put("flip_x",false).put("flip_y",false);}
f.mapper.writeValue(scene.resolve("scene-bank.pack-request.json").toFile(),request);
var registry=(com.fasterxml.jackson.databind.node.ObjectNode)f.mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((com.fasterxml.jackson.databind.node.ArrayNode)registry.path("assets")).addObject().put("asset_id",2).put("asset_uuid",sc.path("asset_uuid").asText()).put("root","scene").put("included_in_build",true);registry.put("next_asset_id",3);f.mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/b_"+f.uuid.toString().replace("-","")+";\n"+"""
import { AnimationError, PlaybackMode, animator_builder } from @core:animation;
import { Composer } from @sdk:composer;
declare global elapsed:int=0;
fn render()->result<AnimationError> {
let a=create_hero(0)!;a.play("idle")!;a.advance(elapsed)!;
let b=animator_builder(0,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!;
b.add_frame(0,2)!;b.add_frame(1,3)!;b.add_frame(2,1)!;b.end_clip()!;
let other=b.build()!;other.play("idle")!;other.advance(elapsed)!;
if other.sprite().glyph_id!=a.sprite().glyph_id {let fail=1/0;}
if Composer.bind_scene(0)!=0 {let fail=1/0;}
let image=a.sprite();let direct=other.sprite();
if Composer.emit_sprite(image.glyph_id,elapsed%2,32,32,0,image.bank_id,false,false,0)!=0 {let fail=1/0;}
if Composer.emit_sprite(direct.glyph_id,elapsed%2,64,32,0,direct.bank_id,false,false,0)!=0 {let fail=1/0;}
elapsed=elapsed+1;return ok(());
}
[Frame]fn frame()->void {render();}
""");
byte[] definition=Files.readAllBytes(f.bankRoot.resolve(AnimationDocument.FILE_NAME));
Path corpus=Path.of(System.getProperty("pbs.registryConformanceDirectory"));Files.createDirectories(corpus);
for(boolean optimized:new boolean[]{false,true}){
p.studio.core.shipper.CompilerBuildGateway compiler=(project,sink)->{
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,project.rootPath().toString()));context.glyphBankLayoutSource=f.layouts;
p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.build(context,p.studio.utilities.logs.LogAggregator.with(sink));
if(!optimized)try{Files.write(context.bytecodeArtifactPath,new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(context.irvm.coherentEmissionPlan()).serialize());}catch(java.io.IOException error){throw new java.io.UncheckedIOException(error);}
return new p.studio.core.shipper.CompilerBuildGateway.CompilerBuildOutput(context.bytecodeArtifactPath,context.irBackend.getReservedMetadata().requiredCapabilities().asList());
};
var build=new StudioShipperService(compiler,f.packer.workspaceService(),f.mapper,new ExecutorOperationExecutor(workers)).prepare(f.project,ignored->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);
assertTrue(build.success(),build.diagnostics().toString());
String prefix="pbs-animation-composer"+(optimized?"-optimized":"");
Files.copy(root.resolve("build/program.pbx"),corpus.resolve(prefix+".pbx"),StandardCopyOption.REPLACE_EXISTING);
Files.copy(root.resolve("build/assets.pa"),corpus.resolve(prefix+".assets.pa"),StandardCopyOption.REPLACE_EXISTING);
Files.copy(build.manifestPath(),corpus.resolve(prefix+".manifest.json"),StandardCopyOption.REPLACE_EXISTING);
String install=System.getProperty("studio.test.runtimeInstall");assertNotNull(install);
var setup=new ProjectLocalStudioSetup(install,null);
var session=new HeadlessProcessGateway(f.mapper,ignored->setup).boot(f.project,"animation-"+optimized,build);
var oracle=f.mapper.createArrayNode();
try{
for(int tick=0;tick<8;tick++){
var outcome=session.advance(1,ignored->{});assertEquals(AutomationOutcome.Kind.SUCCEEDED,outcome.kind(),outcome.toString());
assertNull(session.call(TaskTools.HeadlessAction.FAULT,Map.of()).values().get("fault"));
var frame=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(outcome.capture().png()));
var preview=f.manual.execute(new AnimationService.Request(AnimationService.Operation.PREVIEW,f.project,f.uuid,"hero","idle",(long)tick,tick%2,null,null,null,null)).preview();
var expected=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(preview.image().png()));
var sample=oracle.addObject().put("tick",tick).put("glyph",preview.observation().glyphId()).put("palette",tick%2);
var pixels=sample.putArray("rgba");
for(int y=0;y<16;y++)for(int dx=0;dx<16;dx++){
int pixel=expected.getRGB(dx,y);pixels.add(Integer.toUnsignedLong((pixel<<8)|(pixel>>>24)));
for(int x:new int[]{32,64})assertEquals(pixel,frame.getRGB(x+dx,32+y),"tick "+tick+" at "+x+" optimized="+optimized);
}
}
}finally{session.shutdown().toCompletableFuture().get(10,TimeUnit.SECONDS);}
f.mapper.writeValue(corpus.resolve(prefix+".oracle.json").toFile(),oracle);
assertArrayEquals(definition,Files.readAllBytes(f.bankRoot.resolve(AnimationDocument.FILE_NAME)));
}
}finally{workers.shutdownNow();f.close();}
}
}
@@ -0,0 +1,197 @@
package p.studio.app.animation;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import p.animation.*;
import p.packer.Packer;
import p.packer.messages.*;
import p.studio.api.assets.animation.*;
import p.studio.core.assets.animation.*;
import p.studio.app.assets.PackerGlyphBankLayouts;
import p.studio.app.mcp.*;
import p.studio.core.assets.PackerAssetCatalog;
import p.studio.core.project.*;
import p.studio.core.session.*;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.api.automation.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import static org.junit.jupiter.api.Assertions.*;
import static p.animation.AnimationDocument.*;
class AnimationIntegrationTest {
@TempDir Path root;
final ObjectMapper mapper=new ObjectMapper();
final UUID uuid=UUID.fromString("12345678-1234-1234-1234-123456789abc");
Packer packer;PackerGlyphBankLayouts layouts;DefaultAnimationService engine;ManualAnimationService manual;
p.studio.api.project.ProjectReference project;Path bankRoot;
@BeforeEach void setup()throws Exception{
root=root.toRealPath();bankRoot=Files.createDirectories(root.resolve("assets/hero"));Files.createDirectories(root.resolve("assets/.prometeu"));Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
var manifest=mapper.createObjectNode().put("schema_version",1).put("asset_uuid",uuid.toString()).put("name","hero").put("type","glyph_bank");
manifest.putObject("preload").put("enabled",false);
var output=manifest.putObject("output").put("format","GLYPH/indexed_v1").put("codec","NONE");output.putObject("metadata").put("tile_size","16x16");
output.putObject("pipeline").putArray("palettes").addObject().put("index",0).putObject("palette").putArray("rgba8888").add(0xff0000ff).add(0x00ff00ff).add(0x0000ffff);
var artifacts=manifest.putArray("artifacts");int[] colors={0xffff0000,0xff00ff00,0xff0000ff};
for(int i=0;i<3;i++){var image=new BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,colors[i]);var path=bankRoot.resolve("g"+i+".png");ImageIO.write(image,"png",path.toFile());artifacts.addObject().put("artifact_id","g"+i).put("file","g"+i+".png").put("index",i).put("fingerprint",AnimationRevision.of(Files.readAllBytes(path)));}
mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest);
var registry=mapper.createObjectNode().put("schema_version",1).put("next_asset_id",2);registry.putArray("assets").addObject().put("asset_id",1).put("asset_uuid",uuid.toString()).put("root","hero").put("included_in_build",true);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
packer=Packer.bootstrap(mapper,event->{});layouts=new PackerGlyphBankLayouts(packer.workspaceService(),mapper);
engine=new DefaultAnimationService(layouts,new PackerAssetCatalog(packer.workspaceService()));manual=new ManualAnimationService(engine,path->()->{});
project=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)).openProject(root);
}
@AfterEach void close(){packer.close();}
AnimationDocument document(){var bindings=layouts.resolve(root,uuid).glyphs().stream().map(g->new Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();return new AnimationDocument(1,uuid.toString(),bindings,List.of(new Animator("hero","idle",List.of(new Clip("idle","loop",List.of(new Frame("g0",2),new Frame("g1",3),new Frame("g2",1)))))));}
AnimationService.Request request(AnimationService.Operation op,String revision,AnimationDocument doc,String hash,String bankRevision){return new AnimationService.Request(op,project,uuid,"hero","idle",2L,0,revision,doc,hash,bankRevision);}
@Test void savedDefinitionBuildsARealGeneratedFactoryAndKeepsBinaryAssetsUnchanged()throws Exception{
var context=new PackerProjectContext("app",root);var before=packer.workspaceService().packWorkspace(new PackWorkspaceRequest(context));assertEquals(PackerOperationStatus.SUCCESS,before.status(),before.toString());byte[] binary=Files.readAllBytes(root.resolve("build/assets.pa"));
var saved=manual.execute(AnimationService.Request.save(project,uuid,null,document())).view();assertTrue(saved.diagnostics().isEmpty());
var after=packer.workspaceService().packWorkspace(new PackWorkspaceRequest(context));assertEquals(PackerOperationStatus.SUCCESS,after.status());assertArrayEquals(binary,Files.readAllBytes(root.resolve("build/assets.pa")));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String module="b_"+uuid.toString().replace("-","");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/"+module+";\nimport { AnimationError } from @core:animation;\n"+"""
fn verify() -> result<AnimationError> { let a=create_hero(3)!;a.play("idle")!;a.advance(2)!;
if a.sprite().glyph_id!=1 { let fail=1/0; }return ok(()); }
[Frame] fn frame() -> void { verify(); }
""");
var build=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));build.glyphBankLayoutSource=layouts;
var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(result.bytecodeBytes().length>0);
var source=new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().getFirst();
Path generatedPath=null;String generatedText=null;
for(var id:build.fileTable.identifiers()){var handle=build.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs")){generatedPath=handle.getCanonPath();generatedText=handle.readUtf8().orElseThrow();}}
assertNotNull(generatedPath);assertFalse(generatedText.contains(root.toString()));
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts);
var generated=bridge.currentSource(new p.studio.lsp.messages.LspProjectContext("app","pbs",root),generatedPath).orElseThrow();
assertEquals("generated",generated.origin());assertTrue(generated.readOnly());assertFalse(generated.origins().isEmpty());assertEquals("/animators/0/id",generated.origins().getFirst().jsonPointer());
assertThrows(IllegalStateException.class,()->new p.studio.compiler.workspaces.AssetSurfaceContextLoader().load(root));
Files.createDirectories(root.resolve("src/generated/animations/"+module));Files.writeString(root.resolve("src/generated/animations/"+module+"/mod.barrel"),"pub fn collision() -> void;");Files.writeString(root.resolve("src/generated/animations/"+module+"/main.pbs"),"fn collision() -> void {}");
build=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));build.glyphBankLayoutSource=layouts;
var failed=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(failed.diagnostics().stream().anyMatch(d->d.getCode().equals("E_LINK_GENERATED_COLLISION")),failed.diagnostics().toString());
}
@Test void generatedOriginsRejectStaleRevisionsAndReconnect() throws Exception {
manual.execute(AnimationService.Request.save(project,uuid,null,document()));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
String module="b_"+uuid.toString().replace("-","");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/"+module+";\n[Frame] fn frame()->void { create_hero(1); }");
var calls=new ArrayList<String>();
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts,(r,id,p)->calls.add(id+":"+p));
var context=new p.studio.lsp.messages.LspProjectContext("app","pbs",root);
try(var registry=new p.studio.lsp.services.compiler.ExternalSourceRegistry()){
String consumer=registry.connect(null,false);
String text=Files.readString(root.resolve("src/main.pbs"));
var navigation=bridge.navigation(context,root.resolve("src/main.pbs").toUri().toString(),text,1,29,registry,consumer);
assertEquals(1,navigation.locations().size());String uri=navigation.locations().getFirst().uri();
var content=registry.read(consumer,uri);var origin=content.descriptor().origins().getFirst();
bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer);
assertEquals(List.of(uuid+":/animators/0/id"),calls);
registry.disconnect(consumer);registry.connect(consumer,false);
bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer);
var current=manual.execute(AnimationService.Request.get(project,uuid)).view();
var next=new AnimationDocument(1,uuid.toString(),document().bindings(),List.of());
manual.execute(AnimationService.Request.save(project,uuid,current.revision(),next));
assertThrows(RuntimeException.class,()->bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer));
assertEquals(2,calls.size());
}
}
@Test void conflictsDriftAndExplicitRebindPreserveCanonicalBytes()throws Exception{
var original=document();var saved=manual.execute(AnimationService.Request.save(project,uuid,null,original)).view();byte[] bytes=Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME));
assertThrows(IllegalStateException.class,()->manual.execute(AnimationService.Request.save(project,uuid,null,original)));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
ObjectNode manifest=(ObjectNode)mapper.readTree(bankRoot.resolve("asset.json").toFile());((ObjectNode)manifest.path("artifacts").get(0)).put("index",1);((ObjectNode)manifest.path("artifacts").get(1)).put("index",0);mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest);
var drift=manual.execute(AnimationService.Request.get(project,uuid)).view();assertTrue(drift.diagnostics().stream().anyMatch(d->d.code().equals("binding_drift")));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
var prepared=manual.execute(request(AnimationService.Operation.PREPARE_REBIND,saved.revision(),null,null,null)).proposal();assertEquals(2,prepared.differences().size());
assertThrows(IllegalStateException.class,()->manual.execute(request(AnimationService.Operation.APPLY_REBIND,saved.revision(),prepared.document(),prepared.proposalHash(),"stale-bank")));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
var updated=manual.execute(request(AnimationService.Operation.APPLY_REBIND,saved.revision(),prepared.document(),prepared.proposalHash(),prepared.bankRevision())).view();assertTrue(updated.diagnostics().isEmpty());assertNotEquals(saved.revision(),updated.revision());
}
@Test void utf8ProjectionIsExactDeterministicAndSurvivesBankRelocation() throws Exception {
String clip="idle \"\\\n\r\té😀"+(char)0+(char)1;
var value=new AnimationDocument(1,uuid.toString(),document().bindings(),List.of(
new Animator("zeta",clip,List.of(new Clip(clip,"once",List.of(new Frame("g0",9007199254740993L))))),
new Animator("alpha",clip,List.of(new Clip(clip,"loop",List.of(new Frame("g1",1)))))));
var saved=manual.execute(AnimationService.Request.save(project,uuid,null,value)).view();String bankRevision=saved.bankRevision();
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
Files.writeString(root.resolve("src/main.pbs"),"import {create_zeta,create_alpha} from @app:generated/animations/b_"+uuid.toString().replace("-","")+";[Frame]fn frame()->void {create_zeta(0);create_alpha(0);}");
byte[] previous=null;String generated=null;
for(int repeat=0;repeat<2;repeat++){
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=layouts;
var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(context,p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(result.bytecodeModule().constPool().stream().anyMatch(c->c instanceof p.studio.compiler.backend.bytecode.BytecodeModule.StringConstant text&&text.value().equals(clip)));
if(previous!=null)assertArrayEquals(previous,result.bytecodeBytes());previous=result.bytecodeBytes();
for(var id:context.fileTable.identifiers()){var handle=context.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs"))generated=handle.readUtf8().orElseThrow();}
}
assertNotNull(generated);assertTrue(generated.indexOf("fn create_alpha")<generated.indexOf("fn create_zeta"));assertFalse(generated.contains(root.toString()));
bankRoot=Files.move(bankRoot,root.resolve("assets/renamed"));
var registry=(ObjectNode)mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((ObjectNode)registry.path("assets").get(0)).put("root","renamed");mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
var moved=manual.execute(AnimationService.Request.get(project,uuid)).view();assertEquals(value,moved.document());assertEquals(saved.revision(),moved.revision());assertEquals(bankRevision,moved.bankRevision());assertTrue(moved.diagnostics().isEmpty());
}
@Test void concurrentCreatesAndLateCancelledCallbacksCannotOverwrite() throws Exception {
var pool=Executors.newCachedThreadPool();
try {
var start=new CountDownLatch(1);var results=new ArrayList<Future<Boolean>>();
for(int i=0;i<2;i++)results.add(pool.submit(()->{start.await();try{manual.execute(AnimationService.Request.save(project,uuid,null,document()));return true;}catch(IllegalStateException conflict){return false;}}));
start.countDown();int accepted=0;for(var result:results)if(result.get(10,TimeUnit.SECONDS))accepted++;
assertEquals(1,accepted);byte[] original=Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME));
var entered=new CountDownLatch(1);var release=new CountDownLatch(1);var settled=new CountDownLatch(1);
GlyphBankLayoutSource delayed=new GlyphBankLayoutSource(){
public GlyphBankLayout resolve(Path path,UUID id){return layouts.resolve(path,id);}
public <T>T withLayout(Path path,UUID id,java.util.function.Function<GlyphBankLayout,T> work){
return layouts.withLayout(path,id,bank->{entered.countDown();try{release.await(10,TimeUnit.SECONDS);return work.apply(bank);}catch(InterruptedException error){throw new RuntimeException(error);}finally{settled.countDown();}});
}
};
var session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(pool));var access=new ProjectAccessRegistry();access.register(root,session::enterManual,()->!session.snapshot().closed(),session);
var taskService=new TaskAnimationService(access,new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)),new DefaultAnimationService(delayed,new PackerAssetCatalog(packer.workspaceService())));
session.grant(false).toCompletableFuture().get();String task=session.acquire().task().value();
String revision=AnimationRevision.of(original);
var call=pool.submit(()->taskService.execute(root,task,p->AnimationService.Request.save(p,uuid,revision,document())));
assertTrue(entered.await(5,TimeUnit.SECONDS));
session.reclaim().toCompletableFuture().get(5,TimeUnit.SECONDS);
release.countDown();assertTrue(settled.await(5,TimeUnit.SECONDS));
assertThrows(ExecutionException.class,()->call.get(5,TimeUnit.SECONDS));
assertArrayEquals(original,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
session.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS);
} finally {pool.shutdownNow();}
}
@Test void excludedAndMalformedDefinitionsDoNotProduceStaleFactories()throws Exception{
manual.execute(AnimationService.Request.save(project,uuid,null,document()));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");Files.writeString(root.resolve("src/main.pbs"),"[Frame]fn frame()->void {}");
Files.writeString(bankRoot.resolve(AnimationDocument.FILE_NAME),"{broken");
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=layouts;
var failed=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(context,p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(failed.diagnostics().stream().anyMatch(d->d.getCode().equals("E_ANIMATION_SURFACE")));
var registry=(ObjectNode)mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((ObjectNode)registry.path("assets").get(0)).put("included_in_build",false);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
assertTrue(new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().isEmpty());
assertNull(manual.execute(AnimationService.Request.get(project,uuid)).view().document());
}
@Test void taskToolsShareDocumentsPreviewAndExistingAuthority()throws Exception{
var workers=Executors.newCachedThreadPool();var session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(workers));var access=new ProjectAccessRegistry();access.register(root,session::enterManual,()->!session.snapshot().closed(),session);
var guarded=new ManualAnimationService(engine,access);var saved=guarded.execute(AnimationService.Request.save(project,uuid,null,document())).view();
var preview=guarded.execute(request(AnimationService.Operation.PREVIEW,null,null,null,null)).preview();
var catalog=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper));var tasks=new TaskAnimationService(access,catalog,engine);var tools=new McpToolRegistry(new McpToolCatalog(mapper),mapper,McpAnimationTools.handlers(tasks,mapper));
try {
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId","stale").put("operation","get").put("assetUuid",uuid.toString());
assertEquals("INVALID_TASK",tools.call("studio_animation_query",args).wire().path("structuredContent").path("error").path("code").asText());
session.grant(false).toCompletableFuture().join();String task=session.acquire().task().value();args.put("taskId",task);
assertThrows(ControlDeniedException.class,()->guarded.execute(AnimationService.Request.get(project,uuid)));
var get=tools.call("studio_animation_query",args).wire();assertFalse(get.path("isError").asBoolean(),get.toString());assertEquals(saved.revision(),get.path("structuredContent").path("value").path("view").path("revision").asText());
args.put("operation","preview").put("animatorId","hero").put("clipName","idle").put("elapsedTicks",2L).put("paletteId",0);
var rendered=tools.call("studio_animation_query",args).wire();assertFalse(rendered.path("isError").asBoolean(),rendered.toString());assertArrayEquals(preview.image().png(),Base64.getDecoder().decode(rendered.path("content").get(1).path("data").asText()));
assertEquals(1,rendered.path("structuredContent").path("value").path("preview").path("observation").path("glyphId").asInt());
var save=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("operation","save").put("assetUuid",uuid.toString()).put("expectedRevision","stale");save.set("document",mapper.readTree(new AnimationCodec().encode(document())));
assertEquals("ANIMATION_CONFLICT",tools.call("studio_animation_update",save).wire().path("structuredContent").path("error").path("code").asText());
save.put("expectedRevision",saved.revision());
var published=tools.call("studio_animation_update",save).wire();assertFalse(published.path("isError").asBoolean(),published.toString());
assertEquals(document(),new AnimationCodec().decode(published.path("structuredContent").path("value").path("view").path("json").asText()));
session.release(session.snapshot().task()).toCompletableFuture().get(5,TimeUnit.SECONDS);
assertEquals("INVALID_TASK",tools.call("studio_animation_update",save).wire().path("structuredContent").path("error").path("code").asText());
}finally{session.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS);workers.shutdownNow();}
}
}
@@ -0,0 +1,47 @@
package p.studio.app.animation;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import p.animation.*;
import p.packer.Packer;
import p.packer.messages.*;
import p.studio.api.assets.animation.*;
import p.studio.core.assets.animation.*;
import p.studio.app.assets.PackerGlyphBankLayouts;
import p.studio.app.mcp.*;
import p.studio.core.assets.PackerAssetCatalog;
import p.studio.core.project.*;
import p.studio.core.session.*;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.api.automation.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import static p.animation.AnimationDocument.*;
public class AnimationProjectFixture {
Path root;
final ObjectMapper mapper=new ObjectMapper();
final UUID uuid=UUID.fromString("12345678-1234-1234-1234-123456789abc");
Packer packer;PackerGlyphBankLayouts layouts;DefaultAnimationService engine;ManualAnimationService manual;
p.studio.api.project.ProjectReference project;Path bankRoot;
void setup()throws Exception{
root=root.toRealPath();bankRoot=Files.createDirectories(root.resolve("assets/hero"));Files.createDirectories(root.resolve("assets/.prometeu"));Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
var manifest=mapper.createObjectNode().put("schema_version",1).put("asset_uuid",uuid.toString()).put("name","hero").put("type","glyph_bank");
manifest.putObject("preload").put("enabled",false);
var output=manifest.putObject("output").put("format","GLYPH/indexed_v1").put("codec","NONE");output.putObject("metadata").put("tile_size","16x16");
output.putObject("pipeline").putArray("palettes").addObject().put("index",0).putObject("palette").putArray("rgba8888").add(0xff0000ff).add(0x00ff00ff).add(0x0000ffff);
var artifacts=manifest.putArray("artifacts");int[] colors={0xffff0000,0xff00ff00,0xff0000ff};
for(int i=0;i<3;i++){var image=new BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,colors[i]);var path=bankRoot.resolve("g"+i+".png");ImageIO.write(image,"png",path.toFile());artifacts.addObject().put("artifact_id","g"+i).put("file","g"+i+".png").put("index",i).put("fingerprint",AnimationRevision.of(Files.readAllBytes(path)));}
mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest);
var registry=mapper.createObjectNode().put("schema_version",1).put("next_asset_id",2);registry.putArray("assets").addObject().put("asset_id",1).put("asset_uuid",uuid.toString()).put("root","hero").put("included_in_build",true);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
packer=Packer.bootstrap(mapper,event->{});layouts=new PackerGlyphBankLayouts(packer.workspaceService(),mapper);
engine=new DefaultAnimationService(layouts,new PackerAssetCatalog(packer.workspaceService()));manual=new ManualAnimationService(engine,path->()->{});
project=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)).openProject(root);
}
void close(){packer.close();}
AnimationDocument document(){var bindings=layouts.resolve(root,uuid).glyphs().stream().map(g->new Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();return new AnimationDocument(1,uuid.toString(),bindings,List.of(new Animator("hero","idle",List.of(new Clip("idle","loop",List.of(new Frame("g0",2),new Frame("g1",3),new Frame("g2",1)))))));}
}
@@ -117,20 +117,21 @@ public final class InstalledKnowledgeProbe {
check(linkedResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed Linked example must compile");
Files.write(fixtures.resolve("pbs-linked-installed.pbx"),linkedResult.bytecodeBytes());
System.out.println("Installed Linked execution fixture generated");
for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs").entrySet()) {
for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs","animation","animation.pbs").entrySet()) {
Path exampleRoot=Files.createDirectory(Path.of(example.getKey()+"-example")).toRealPath();
Files.createDirectories(exampleRoot.resolve("src"));
Files.copy(root.resolve("prometeu.json"),exampleRoot.resolve("prometeu.json"));
Files.writeString(exampleRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String function=switch(example.getKey()){case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";};
String function=switch(example.getKey()){case "animation"->"animationExample";case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";};
Files.writeString(exampleRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/"+example.getValue()))
+"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}");
+(example.getKey().equals("animation")?"\n[Frame] fn frame()->void { animationExample(); }":"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}"));
var exampleResult=BuilderPipelineService.INSTANCE.compile(
BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,exampleRoot.toString())),LogAggregator.stdout());
check(exampleResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed "+example.getKey()+" example must compile: "+exampleResult.diagnostics());
Files.write(fixtures.resolve("pbs-"+example.getKey()+"-installed.pbx"),exampleResult.bytecodeBytes());
System.out.println("Installed "+example.getKey()+" execution fixture generated");
}
p.studio.app.animation.AnimationInstalledProbe.verify(Files.createDirectory(Path.of("animation-authored")).toRealPath(),fixtures);
verifyExternalSources(provider.getClass().getClassLoader());
registration.unsubscribe();
System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled");
@@ -21,6 +21,8 @@ class InstalledKnowledgeTest {
assertTrue(log.contains("Installed map execution fixture generated"), log);
assertTrue(log.contains("Installed stack-queue execution fixture generated"), log);
assertTrue(log.contains("Installed memcard execution fixture generated"), log);
assertTrue(log.contains("Installed animation execution fixture generated"), log);
assertTrue(log.contains("Installed generated animation verified"), log);
}
@Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception {
@@ -12,7 +12,7 @@ class McpContractTest {
final McpToolCatalog catalog = new McpToolCatalog(mapper);
@Test void everyToolHasValidExampleAuthorityAndResultEnvelope() {
assertEquals(22, catalog.names().size());
assertEquals(24, catalog.names().size());
for (var name : catalog.names()) {
var definition = catalog.definition(name);
assertDoesNotThrow(() -> catalog.validateArguments(name, definition.get("exampleArguments")), name + " arguments");
@@ -27,7 +27,7 @@ class StudioMcpStdioTest {
var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100);
try (var process = new Connector(root); var server = server(count, pixels)) {
process.initialize();
assertEquals(22, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
assertEquals(24, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
var waiting = process.call("studio_project_context", root);
assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText());
assertFalse(Files.exists(root.resolve(".studio")));