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
@@ -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")));