feat(studio): deliver asset authoring and automation workflows
Add shared human/task asset batches with reviewed atomic publication, explicit reference rebinds, ownership inspection and qualified glyph/scene budgets. Expose the same authoring and capacity results through Assets and MCP. Deliver isolated guest test targets, retained visual evidence and immutable runtime lifecycle/control observations. Preserve provider qualification and installed authoring examples alongside the completed discussion lessons. Close AGD-106 coordination and the delivered discussion workflows through housekeeping, updating lesson references and preserving qualification limits. Sound remains outside the asset delivery wave. Validation: 579 module tests and 31 additional desktop, process and installed checks passed; native glyph/scene 16/17 boundaries qualified. Discussion validation passed after housekeeping.
This commit is contained in:
@@ -63,7 +63,16 @@ javafx {
|
||||
}
|
||||
|
||||
// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests.
|
||||
tasks.named<Test>("test") { exclude("**/AnimationDesktopTest.class", "**/AnimationInstalledRuntimeTest.class", "**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/GuestTestsInstalledRuntimeTest.class", "**/AssetAuthoringDesktopTest.class", "**/AnimationDesktopTest.class", "**/AnimationInstalledRuntimeTest.class", "**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") }
|
||||
tasks.register<Test>("assetAuthoringDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Inspects and qualifies the actual Assets authoring workspace (requires a display)."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/AssetAuthoringDesktopTest.class")
|
||||
systemProperty("java.awt.headless", "false")
|
||||
}
|
||||
tasks.register<Test>("devDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)."
|
||||
@@ -106,6 +115,7 @@ tasks.register<Test>("headlessProcessTest") {
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/HeadlessInstalledRuntimeTest.class")
|
||||
include("**/GuestTestsInstalledRuntimeTest.class")
|
||||
include("**/AnimationInstalledRuntimeTest.class")
|
||||
systemProperty("pbs.registryConformanceDirectory",
|
||||
project(":prometeu-compiler:prometeu-build-pipeline").layout.buildDirectory.dir("registry-conformance").get().asFile.absolutePath)
|
||||
@@ -152,3 +162,39 @@ tasks.register<Test>("installedConnectorTest") {
|
||||
include("**/InstalledConnectorTest.class")
|
||||
systemProperty("studio.test.distribution", layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath)
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/GuestTestPilotTest.class") }
|
||||
tasks.register<Test>("guestTestPilotTest") {
|
||||
group = "verification"
|
||||
description = "Runs isolated public shop/save tests on a disposable copy of the selected actual game."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/GuestTestPilotTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
systemProperty("studio.test.guestPilotProject", providers.gradleProperty("studioGuestPilotProject").getOrElse(""))
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/GuestTestsDesktopTest.class") }
|
||||
tasks.register<Test>("guestTestsDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies the actual Tests workspace and authenticated MCP against the installed provider."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/GuestTestsDesktopTest.class")
|
||||
systemProperty("java.awt.headless", "false")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/AssetCapacityInstalledRuntimeTest.class", "**/AssetManagedBuildInstalledRuntimeTest.class") }
|
||||
tasks.register<Test>("assetCapacityProcessTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies glyph/scene 16/17 boundaries against the exact installed runtime."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/AssetCapacityInstalledRuntimeTest.class")
|
||||
include("**/AssetManagedBuildInstalledRuntimeTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
}
|
||||
|
||||
@@ -111,13 +111,27 @@ public class StudioApplicationConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
|
||||
return new PackerAssetPacking(packer, operations, access);
|
||||
p.studio.app.assets.AssetBudgetInspection assetBudgetInspection(ObjectMapper mapper,PackerWorkspaceService packer,ProjectLocalStudioSetupStore setup) {
|
||||
return new p.studio.app.assets.AssetBudgetInspection(mapper,packer,setup::load);
|
||||
}
|
||||
@Bean
|
||||
p.studio.core.assets.AssetBatchWorkspace assetBatchWorkspace(ObjectMapper mapper,PackerWorkspaceService packer,p.studio.app.assets.AssetBudgetInspection budgets) {
|
||||
return new p.studio.app.assets.FileAssetBatchWorkspace(mapper,packer,budgets::inspect);
|
||||
}
|
||||
@Bean
|
||||
p.studio.api.assets.AssetAuthoringService assetAuthoringService(p.studio.core.project.ProjectAccessRegistry projects,ProjectCatalog catalog,
|
||||
p.studio.core.assets.AssetBatchWorkspace workspace,OperationExecutor operations) {
|
||||
return new p.studio.core.assets.DefaultAssetAuthoringService(projects,catalog,workspace,operations);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access,p.studio.app.assets.AssetBudgetInspection budgets) {
|
||||
return new PackerAssetPacking(packer, operations, access).withAssetPreflight(budgets);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AssetDetails assetDetails(PackerWorkspaceService packer) {
|
||||
return new PackerAssetDetails(packer);
|
||||
return new PackerAssetDetails(packer,false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -146,8 +160,8 @@ public class StudioApplicationConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
AssetMetadataService assetMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
|
||||
return new AssetStudioMetadataService(mapper, access);
|
||||
AssetMetadataService assetMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access,PackerWorkspaceService packer) {
|
||||
return new AssetStudioMetadataService(mapper, access,packer);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -197,8 +211,8 @@ public class StudioApplicationConfiguration {
|
||||
|
||||
@Bean
|
||||
StudioShipperService shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper,
|
||||
OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
|
||||
return new StudioShipperService(compiler, packer, mapper, operations, access);
|
||||
OperationExecutor operations, p.studio.api.automation.ProjectAccess access,p.studio.app.assets.AssetBudgetInspection budgets) {
|
||||
return new StudioShipperService(compiler, packer, mapper, operations, access).withAssetPreflight(budgets);
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "shutdown")
|
||||
@@ -252,8 +266,13 @@ public class StudioApplicationConfiguration {
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations,
|
||||
p.studio.api.automation.AutomationConnectionLifecycle connections,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations, connections, preparation);
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation, p.studio.api.automation.EvidenceTools evidence,
|
||||
p.studio.api.automation.GuestTestTools tests,p.studio.api.assets.AssetAuthoringService authoring) {
|
||||
var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations, connections, preparation);
|
||||
factory.setEvidenceTools(evidence);
|
||||
factory.setGuestTestTools(tests);
|
||||
factory.setAssetAuthoring(authoring);
|
||||
return factory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -350,14 +369,35 @@ public class StudioApplicationConfiguration {
|
||||
return new p.studio.core.session.DefaultTaskTools(projects, catalog, shipper, headless);
|
||||
}
|
||||
|
||||
@Bean
|
||||
p.studio.api.automation.EvidenceTools evidenceTools(p.studio.core.project.ProjectAccessRegistry projects,
|
||||
p.studio.api.automation.TaskTools tasks, ObjectMapper mapper) {
|
||||
return new p.studio.core.session.DefaultEvidenceTools(projects, tasks,
|
||||
new p.studio.app.evidence.FileEvidenceStore(mapper), new p.studio.app.evidence.PngEvidenceCodec());
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "close")
|
||||
p.studio.core.session.DefaultGuestTestTools guestTestTools(p.studio.core.project.ProjectAccessRegistry projects,
|
||||
ProjectCatalog catalog, p.studio.core.shipper.SavedProjectPreparation shipper,
|
||||
p.studio.core.runtime.HeadlessGateway gateway, ObjectMapper mapper, OperationExecutor operations) {
|
||||
var support = new p.studio.app.runtime.GuestTestSupportAdapter(mapper,
|
||||
new p.studio.app.evidence.FileEvidenceStore(mapper),new p.studio.app.evidence.PngEvidenceCodec());
|
||||
return new p.studio.core.session.DefaultGuestTestTools(projects,catalog,shipper,gateway,support,
|
||||
new p.studio.app.runtime.GuestEventDecoder(mapper),operations);
|
||||
}
|
||||
|
||||
@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, p.studio.api.assets.animation.AnimationTasks animations, java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
|
||||
p.studio.api.automation.TaskTools tasks, p.studio.api.assets.animation.AnimationTasks animations,
|
||||
p.studio.api.automation.EvidenceTools evidence, p.studio.api.automation.GuestTestTools tests,p.studio.api.assets.AssetAuthoringService assets, 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));
|
||||
handlers.putAll(p.studio.app.mcp.McpEvidenceTools.handlers(evidence, mapper));
|
||||
if(headless.isPresent())handlers.putAll(p.studio.app.mcp.McpGuestTestTools.handlers(tests,mapper));
|
||||
handlers.putAll(p.studio.app.mcp.McpAssetAuthoringTools.handlers(assets,mapper));
|
||||
return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import p.packer.dtos.PackerDiagnosticDTO;
|
||||
import p.studio.api.assets.AssetBatches;
|
||||
import p.studio.api.assets.AssetFamily;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Projects only emitted producer facts. No text parsing or inferred missing indices. */
|
||||
final class AssetBatchDiagnostics {
|
||||
static AssetBatches.Diagnostic from(PackerDiagnosticDTO source,Path staged,Path published) {
|
||||
var context=new LinkedHashMap<String,Object>(source.context());
|
||||
String root=context.get("assetRoot") instanceof String value?translate(value,staged,published):null;
|
||||
String path=source.evidencePath()==null?null:translate(source.evidencePath().toString(),staged,published);
|
||||
if(root!=null)context.put("assetRoot",root);
|
||||
AssetFamily family=null;if(context.get("family") instanceof String value)try{family=AssetFamily.valueOf(value);}catch(IllegalArgumentException ignored){}
|
||||
return new AssetBatches.Diagnostic("packer",Objects.requireNonNullElse(source.code(),"PACKER_DIAGNOSTIC"),source.severity().name(),source.message(),source.blocking(),root,path,family,
|
||||
indices(context.get("missingIndices")),indices(context.get("duplicateIndices")),List.of(),number(context.get("used")),number(context.get("required")),number(context.get("limit")),context);
|
||||
}
|
||||
private static List<Integer> indices(Object value){return value instanceof List<?> list?list.stream().filter(Number.class::isInstance).map(n->((Number)n).intValue()).toList():List.of();}
|
||||
private static Long number(Object value){return value instanceof Number n?n.longValue():null;}
|
||||
private static String translate(String value,Path from,Path to){Path path=Path.of(value);return path.startsWith(from)?to.resolve(from.relativize(path)).toString():value;}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.annotation.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.AssetBatches;
|
||||
|
||||
/** Persistence/transport tagging belongs to the adapter, not the neutral asset API. */
|
||||
public final class AssetBatchJson {
|
||||
private AssetBatchJson(){}
|
||||
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,property="kind")
|
||||
@JsonSubTypes({@JsonSubTypes.Type(value=AssetBatches.CreateBank.class,name="create_bank"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.RegisterBank.class,name="register_bank"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.ImportPng.class,name="import_png"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.ComposeBank.class,name="compose_bank"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.ComposeScene.class,name="compose_scene"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.ComposePalettes.class,name="compose_palettes"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.UpdateContract.class,name="update_contract"),
|
||||
@JsonSubTypes.Type(value=AssetBatches.BuildParticipation.class,name="build_participation")})
|
||||
private interface Mutation {}
|
||||
private interface Reference {
|
||||
@JsonIgnore boolean isAssetIdReference();
|
||||
@JsonIgnore boolean isAssetRootReference();
|
||||
}
|
||||
public static ObjectMapper mapper(ObjectMapper source){
|
||||
var module=new com.fasterxml.jackson.databind.module.SimpleModule();
|
||||
module.addSerializer(p.studio.api.assets.AssetReference.class,new com.fasterxml.jackson.databind.JsonSerializer<>(){
|
||||
@Override public void serialize(p.studio.api.assets.AssetReference value,com.fasterxml.jackson.core.JsonGenerator out,com.fasterxml.jackson.databind.SerializerProvider provider)throws java.io.IOException{out.writeString(value.value());}
|
||||
});
|
||||
module.addDeserializer(p.studio.api.assets.AssetReference.class,new com.fasterxml.jackson.databind.JsonDeserializer<>(){
|
||||
@Override public p.studio.api.assets.AssetReference deserialize(com.fasterxml.jackson.core.JsonParser parser,com.fasterxml.jackson.databind.DeserializationContext context)throws java.io.IOException {
|
||||
com.fasterxml.jackson.databind.JsonNode node=parser.readValueAsTree();return p.studio.api.assets.AssetReference.of(node.isTextual()?node.textValue():node.path("value").asText());
|
||||
}
|
||||
});
|
||||
return source.copy().addMixIn(AssetBatches.Mutation.class,Mutation.class).addMixIn(p.studio.api.assets.AssetReference.class,Reference.class).registerModule(module);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.core.assets.scene.SceneBankWorkflowService;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Calls the existing asset commands and canonical scene emitter on the candidate workspace. */
|
||||
final class AssetBatchMutations {
|
||||
private final AssetCommands commands;private final AssetCatalog catalog;private final AssetMetadataService metadata;
|
||||
private final ObjectMapper json;private final AssetPngSources sources;
|
||||
private final p.packer.PackerWorkspaceService packer;
|
||||
AssetBatchMutations(AssetCommands commands,AssetCatalog catalog,AssetMetadataService metadata,ObjectMapper json,AssetPngSources sources,p.packer.PackerWorkspaceService packer) {
|
||||
this.commands=commands;this.catalog=catalog;this.metadata=metadata;this.json=json;this.sources=sources;this.packer=packer;
|
||||
}
|
||||
AssetSummary asset(ProjectReference project,AssetReference reference) {
|
||||
return catalog.list(project,false).stream().filter(a->a.reference().equals(reference)
|
||||
||reference.isAssetRootReference()&&project.rootPath().resolve("assets").resolve(reference.rawValue()).normalize().equals(a.root()))
|
||||
.findFirst().orElseThrow(()->new IllegalArgumentException("Unknown asset: "+reference.value()));
|
||||
}
|
||||
void apply(ProjectReference original,ProjectReference stage,Mutation mutation)throws Exception {
|
||||
switch(mutation) {
|
||||
case CreateBank c -> {
|
||||
if(c.family()!=AssetFamily.GLYPH_BANK&&c.family()!=AssetFamily.SCENE_BANK)throw new IllegalArgumentException("This wave supports glyph and scene authoring");
|
||||
check(commands.create(stage,c.relativeRoot(),c.name(),c.family(),c.outputFormat(),c.outputCodec(),c.preload()));
|
||||
}
|
||||
case RegisterBank r -> check(commands.register(stage,r.bank()));
|
||||
case ImportPng i -> {
|
||||
var bank=asset(stage,i.bank());if(bank.family()!=AssetFamily.GLYPH_BANK)throw new IllegalArgumentException("PNG import requires a glyph bank");
|
||||
String relative=stage.rootPath().relativize(bank.root()).resolve(i.destination()).toString();
|
||||
Path destination=AssetWorkspaceFiles.path(stage.rootPath(),relative);byte[] bytes=sources.bytes(original.rootPath(),i.source());
|
||||
Files.createDirectories(destination.getParent());Files.write(destination,bytes);
|
||||
var declaration=json.readTree(bank.root().resolve("asset.json").toFile());var selected=new ArrayList<String>();
|
||||
declaration.path("artifacts").forEach(a->selected.add(a.path("file").asText()));
|
||||
if(selected.contains(i.destination()))check(commands.applyBankComposition(stage,bank.reference(),selected));
|
||||
}
|
||||
case ComposeBank c -> {
|
||||
var bank=asset(stage,c.bank());if(bank.family()!=AssetFamily.GLYPH_BANK)throw new IllegalArgumentException("PNG composition requires a glyph bank");
|
||||
for(String path:c.selectedPaths())AssetWorkspaceFiles.path(stage.rootPath(),stage.rootPath().relativize(bank.root()).resolve(path).toString());
|
||||
check(commands.applyBankComposition(stage,bank.reference(),c.selectedPaths()));
|
||||
}
|
||||
case ComposePalettes p -> {
|
||||
var bank=asset(stage,p.bank());if(bank.family()!=AssetFamily.GLYPH_BANK)throw new IllegalArgumentException("Palette composition requires a glyph bank");
|
||||
check(commands.applyPaletteOverhauling(stage,bank.reference(),p.palettes().stream().map(palette->Map.<String,Object>of("index",palette.index(),"rgba8888",palette.rgba8888())).toList()));
|
||||
}
|
||||
case ComposeScene c -> {
|
||||
var bank=asset(stage,c.bank());if(bank.family()!=AssetFamily.SCENE_BANK)throw new IllegalArgumentException("Scene composition requires a scene bank");
|
||||
var layers=new ArrayList<AssetStudioSceneLayerBinding>();int index=1;
|
||||
for(var layer:c.layers()) {
|
||||
String glyph="";if(layer.glyphBank()!=null){var source=asset(stage,layer.glyphBank());if(source.family()!=AssetFamily.GLYPH_BANK)throw new IllegalArgumentException("Scene source must be a glyph bank");glyph=stage.rootPath().resolve("assets").relativize(source.root()).toString();}
|
||||
var tiles=new ArrayList<AssetStudioSceneTile>();
|
||||
for(var tile:layer.tiles()) {
|
||||
if(!tile.active()){tiles.add(AssetStudioSceneTile.inactive(tile.paletteId()));continue;}
|
||||
var source=asset(stage,tile.artifact().bank());var layerSource=asset(stage,layer.glyphBank());
|
||||
if(!source.reference().equals(layerSource.reference()))throw new IllegalArgumentException("Tile artifact does not belong to its declared layer bank");
|
||||
var layout=packer.getGlyphBankLayout(new p.packer.messages.GetGlyphBankLayoutRequest(new p.packer.messages.PackerProjectContext(stage.name(),stage.rootPath()),UUID.fromString(source.assetUuid())));
|
||||
var selected=layout.glyphs().stream().filter(g->g.artifactId().equals(tile.artifact().artifactId())).findFirst().orElseThrow(()->new IllegalArgumentException("Unknown scene tile artifact"));
|
||||
if(layer.tileSize()!=0&&layer.tileSize()!=selected.width())throw new IllegalArgumentException("Tile geometry differs from the declared layer size");
|
||||
tiles.add(new AssetStudioSceneTile(true,selected.glyphId(),tile.paletteId(),tile.flipX(),tile.flipY()));
|
||||
}
|
||||
layers.add(new AssetStudioSceneLayerBinding(layer.active(),index,"Layer "+index,layer.width(),layer.height(),"scene.tmx",glyph,layer.parallaxFactorX(),layer.parallaxFactorY(),0,tiles));index++;
|
||||
}
|
||||
var value=new AssetStudioSceneBankMetadata(layers.getFirst().width(),layers.getFirst().height(),4,layers,bank.root().resolve("scene-bank.studio.json"));
|
||||
var written=metadata.writeSceneBankMetadata(bank.root(),value);if(!written.successful())throw new IllegalArgumentException(written.message());
|
||||
new SceneBankWorkflowService(catalog,json).writeComposition(stage,bank.root(),value);
|
||||
}
|
||||
case UpdateContract c -> {var bank=asset(stage,c.bank());check(commands.updateContract(stage,bank.reference(),c.preload(),c.outputCodec(),c.codecFields(),c.metadataFields()));}
|
||||
case BuildParticipation b -> check(commands.updateBuildParticipation(stage,b.bank(),b.included()));
|
||||
}
|
||||
}
|
||||
private static void check(AssetMutationResult result){if(result.status()!=AssetOperationStatus.SUCCESS)throw new IllegalArgumentException(result.summary());}
|
||||
private static void check(AssetUpdateResult result){if(!result.success())throw new IllegalArgumentException(result.errorMessage());}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.assets.metadata.AssetMetadataService;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.core.assets.scene.SceneBankWorkflowService;
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Actual animation/material/scene references are enumerated before any incompatible publication. */
|
||||
final class AssetBatchReferences {
|
||||
record Glyph(Artifact identity,int index,String fingerprint,String content){}
|
||||
private final AssetCatalog catalog;private final AssetMetadataService metadata;private final PackerWorkspaceService packer;private final ObjectMapper json;
|
||||
AssetBatchReferences(AssetCatalog catalog,AssetMetadataService metadata,PackerWorkspaceService packer,ObjectMapper json) {
|
||||
this.catalog=catalog;this.metadata=metadata;this.packer=packer;this.json=json;
|
||||
}
|
||||
Map<Artifact,Glyph> glyphs(ProjectReference project)throws Exception {
|
||||
var result=new LinkedHashMap<Artifact,Glyph>();
|
||||
for(var bank:catalog.list(project,false))if(bank.family()==AssetFamily.GLYPH_BANK) {
|
||||
var manifest=json.readTree(bank.root().resolve("asset.json").toFile());String contract=manifest.path("output").toString();
|
||||
for(var artifact:manifest.path("artifacts")) {
|
||||
String id=artifact.path("artifact_id").asText();if(id.isEmpty())continue;
|
||||
Path file=AssetWorkspaceFiles.path(project.rootPath(),project.rootPath().relativize(bank.root()).resolve(artifact.path("file").asText()).toString());
|
||||
String content=AssetWorkspaceFiles.hash((contract+":"+artifact.path("file").asText()+":"+(Files.isRegularFile(file)?AssetWorkspaceFiles.hash(Files.readAllBytes(file)):"missing")).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
var identity=new Artifact(bank.reference(),id);result.put(identity,new Glyph(identity,artifact.path("index").asInt(),artifact.path("fingerprint").asText(),content));
|
||||
}
|
||||
}return result;
|
||||
}
|
||||
List<ReferenceUse> uses(ProjectReference project,Map<Artifact,Glyph> glyphs)throws Exception {
|
||||
var assets=catalog.list(project,false);var result=new ArrayList<ReferenceUse>();
|
||||
for(var owner:assets) {
|
||||
for(String file:List.of("animations.studio.json","glyph-material.json","studio.asset.json")) {
|
||||
Path path=owner.root().resolve(file);if(!Files.exists(path))continue;
|
||||
scan(json.readTree(path.toFile()),"",project.rootPath().relativize(path).toString(),owner.reference(),file.startsWith("animations")?ReferenceKind.animation:ReferenceKind.metadata,result);
|
||||
}
|
||||
Path scene=owner.root().resolve("scene-bank.studio.json");if(!Files.exists(scene))continue;
|
||||
var layers=json.readTree(scene.toFile()).path("layers");int layer=0;
|
||||
for(var node:layers) {
|
||||
String target=node.path("tileset_asset_root").asText();
|
||||
var source=assets.stream().filter(a->a.root().equals(project.rootPath().resolve("assets").resolve(target).normalize())).findFirst().orElse(null);
|
||||
if(source!=null&&node.path("enabled").asBoolean()) {
|
||||
int tile=0;for(var value:node.path("tiles")) {
|
||||
int index=value.path("glyph_id").asInt();
|
||||
if(value.path("active").asBoolean()) {
|
||||
var glyph=glyphs.values().stream().filter(g->g.identity().bank().equals(source.reference())&&g.index()==index).findFirst().orElse(null);
|
||||
if(glyph!=null)result.add(new ReferenceUse(owner.reference(),ReferenceKind.scene,project.rootPath().relativize(scene)+"#/layers/"+layer+"/tiles/"+tile,glyph.identity()));
|
||||
}tile++;
|
||||
}
|
||||
}layer++;
|
||||
}
|
||||
}return result;
|
||||
}
|
||||
private void scan(JsonNode node,String pointer,String file,AssetReference owner,ReferenceKind kind,List<ReferenceUse> uses) {
|
||||
if(node.isObject()) {
|
||||
if(node.path("artifact_id").isTextual())uses.add(new ReferenceUse(owner,kind,file+"#"+pointer,new Artifact(owner,node.path("artifact_id").asText())));
|
||||
var fields=node.fields();while(fields.hasNext()){var field=fields.next();scan(field.getValue(),pointer+"/"+field.getKey().replace("~","~0").replace("/","~1"),file,owner,kind,uses);}
|
||||
}else if(node.isArray())for(int i=0;i<node.size();i++)scan(node.get(i),pointer+"/"+i,file,owner,kind,uses);
|
||||
}
|
||||
List<ReferenceUse> apply(ProjectReference original,ProjectReference stage,List<Rebind> rebinds)throws Exception {
|
||||
var before=glyphs(original);var after=glyphs(stage);
|
||||
var affected=uses(original,before).stream().filter(use->{var a=before.get(use.target());var b=after.get(use.target());return b==null||a.index()!=b.index()||!a.content().equals(b.content());}).toList();
|
||||
var explicit=new HashMap<ReferenceUse,Artifact>();
|
||||
for(var rebind:rebinds)for(var reference:rebind.references()) {
|
||||
if(!affected.contains(reference))throw new IllegalArgumentException("Rebind names a reference not affected by this candidate: "+reference.location());
|
||||
if(explicit.put(reference,rebind.to())!=null)throw new IllegalArgumentException("Duplicate reference rebind");
|
||||
if(!after.containsKey(rebind.to()))throw new IllegalArgumentException("Replacement artifact is unavailable: "+rebind.to());
|
||||
}
|
||||
if(!explicit.keySet().containsAll(affected))return affected;
|
||||
var modified=new LinkedHashMap<Path,JsonNode>();var scenes=new HashSet<AssetReference>();
|
||||
for(var use:affected) {
|
||||
var replacement=after.get(explicit.get(use));String[] location=use.location().split("#",2);
|
||||
Path path=AssetWorkspaceFiles.path(stage.rootPath(),location[0]);
|
||||
JsonNode document=modified.computeIfAbsent(path,p->{try{return json.readTree(p.toFile());}catch(Exception error){throw new IllegalStateException(error);}});
|
||||
var node=(ObjectNode)document.at(location[1]);
|
||||
if(use.kind()==ReferenceKind.scene) {
|
||||
node.put("glyph_id",replacement.index());String layerPointer=location[1].substring(0,location[1].indexOf("/tiles/"));
|
||||
var bank=catalog.list(stage,false).stream().filter(a->a.reference().equals(replacement.identity().bank())).findFirst().orElseThrow();
|
||||
((ObjectNode)document.at(layerPointer)).put("tileset_asset_root",stage.rootPath().resolve("assets").relativize(bank.root()).toString());scenes.add(use.owner());
|
||||
}else {
|
||||
if(!use.owner().equals(replacement.identity().bank()))throw new IllegalArgumentException("Animation/material artifacts belong to their containing bank");
|
||||
node.put("artifact_id",replacement.identity().artifactId());
|
||||
if(node.has("glyph_id"))node.put("glyph_id",replacement.index());
|
||||
if(node.has("fingerprint"))node.put("fingerprint",replacement.fingerprint());
|
||||
}
|
||||
}
|
||||
for(var entry:modified.entrySet())AssetWorkspaceFiles.write(json,entry.getKey(),entry.getValue());
|
||||
for(var reference:scenes) {
|
||||
var bank=catalog.list(stage,false).stream().filter(a->a.reference().equals(reference)).findFirst().orElseThrow();
|
||||
new SceneBankWorkflowService(catalog,json).writeComposition(stage,bank.root(),metadata.read(bank.root(),bank.family()).sceneBankMetadata());
|
||||
}
|
||||
validateAnimations(stage);return List.of();
|
||||
}
|
||||
private void validateAnimations(ProjectReference project)throws Exception {
|
||||
var layouts=new PackerGlyphBankLayouts(packer,json);
|
||||
for(var bank:catalog.list(project,false)) {
|
||||
Path file=bank.root().resolve(p.animation.AnimationDocument.FILE_NAME);if(!Files.exists(file))continue;
|
||||
var document=new p.animation.AnimationCodec().decode(Files.readString(file));
|
||||
layouts.withLayout(project.rootPath(),UUID.fromString(bank.assetUuid()),layout->{new p.animation.AnimationValidator().requireValid(document,layout);return null;});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.studio.api.assets.AssetBudgets;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.core.assets.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** One pack-plan snapshot feeds Core policy, UI/MCP queries and build admission. */
|
||||
public final class AssetBudgetInspection implements AssetBuildPreflight {
|
||||
private final PackerWorkspaceService packer;private final AssetCapacityProfiles profiles;
|
||||
private final Function<ProjectReference,ProjectLocalStudioSetup> setup;
|
||||
public AssetBudgetInspection(ObjectMapper json,PackerWorkspaceService packer,Function<ProjectReference,ProjectLocalStudioSetup> setup){this.packer=packer;this.profiles=new AssetCapacityProfiles(json);this.setup=setup;}
|
||||
@Override public AssetBudgets.Snapshot inspect(ProjectReference project) {
|
||||
var context=new PackerProjectContext(project.name(),project.rootPath());
|
||||
return packer.withProject(context,()->{
|
||||
var plan=packer.planPackWorkspace(context);
|
||||
return new AssetBudgetPolicy().evaluate(AssetWorkspaceFiles.revision(project.rootPath()),profiles.select(setup.apply(project)),plan,
|
||||
plan.diagnostics().stream().map(d->AssetBatchDiagnostics.from(d,project.rootPath(),project.rootPath())).toList());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.AssetBudgets.*;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Installed resource profiles only. Ordinary builds never inspect a sibling runtime checkout. */
|
||||
public final class AssetCapacityProfiles {
|
||||
public record Bundle(Profile profile,Map<String,String> executables){}
|
||||
public record Catalog(int schemaVersion,List<Bundle> profiles){}
|
||||
private final ObjectMapper json;
|
||||
public AssetCapacityProfiles(ObjectMapper json){this.json=json;}
|
||||
public ProfileSelection select(ProjectLocalStudioSetup setup) {
|
||||
if(setup==null||setup.prometeuRuntimePath()==null)return ProfileSelection.unknown(null,"No runtime installation selected");
|
||||
String selected=null;
|
||||
try {
|
||||
Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=System.getProperty("os.name").startsWith("Windows")?"prometeu.exe":"prometeu";
|
||||
selected=AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(dispatcher)));
|
||||
try(var stream=getClass().getResourceAsStream("/asset-capacity/catalog.json")) {
|
||||
if(stream==null)return ProfileSelection.unknown(selected,"No distributed capacity profiles");
|
||||
var catalog=json.readValue(stream,Catalog.class);if(catalog.schemaVersion()!=1)throw new IllegalArgumentException("Unsupported profile catalog");
|
||||
for(var bundle:catalog.profiles())if(bundle.profile().executableSha256().equals(selected)) {
|
||||
if(!bundle.executables().keySet().containsAll(Set.of("prometeu","prometeu-headless","prometeu-runtime")))throw new IllegalArgumentException("Incomplete executable identity");
|
||||
for(var entry:bundle.executables().entrySet()) {
|
||||
if(!Set.of("prometeu","prometeu-headless","prometeu-runtime").contains(entry.getKey()))throw new IllegalArgumentException("Unsupported executable identity");
|
||||
if(!AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(entry.getKey()))).equals(entry.getValue()))return ProfileSelection.unknown(selected,"Runtime component changed: "+entry.getKey());
|
||||
}
|
||||
for(var evidence:bundle.profile().evidence())try(var record=getClass().getClassLoader().getResourceAsStream(evidence.evidencePath())) {
|
||||
if(record==null||!AssetWorkspaceFiles.hash(record.readAllBytes()).equals(evidence.evidenceSha256()))throw new IllegalArgumentException("Capacity evidence integrity mismatch");
|
||||
}
|
||||
return new ProfileSelection(QualificationState.known,selected,bundle.profile(),"Exact qualified dispatcher and runtime components match");
|
||||
}
|
||||
}
|
||||
return ProfileSelection.unknown(selected,"Selected executable has no qualified capacity profile");
|
||||
}catch(Exception invalid){return ProfileSelection.unknown(selected,"Capacity profile unavailable or invalid: "+Objects.requireNonNullElse(invalid.getMessage(),invalid.getClass().getSimpleName()));}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.Ownership;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Descriptive generation graph. No edge executes a producer or a dependent operation. */
|
||||
final class AssetOwnershipGraph {
|
||||
record Record(Ownership ownership,Map<String,String> dependencyInputs,String outputHash){}
|
||||
private final ObjectMapper json;private final AssetCatalog catalog;
|
||||
AssetOwnershipGraph(ObjectMapper json,AssetCatalog catalog){this.json=json;this.catalog=catalog;}
|
||||
private List<Record> records(ProjectReference project)throws Exception {
|
||||
Path file=AssetWorkspaceFiles.path(project.rootPath(),AssetWorkspaceFiles.OWNERSHIP);
|
||||
return Files.exists(file)?List.of(json.readValue(file.toFile(),Record[].class)):List.of();
|
||||
}
|
||||
AssetReference resolve(ProjectReference project,AssetReference reference) {
|
||||
return catalog.list(project,false).stream().filter(a->a.reference().equals(reference)||reference.isAssetRootReference()&&project.rootPath().resolve("assets").resolve(reference.rawValue()).normalize().equals(a.root())).findFirst().orElseThrow(()->new IllegalArgumentException("Unknown ownership bank: "+reference.value())).reference();
|
||||
}
|
||||
private Map<String,String> inputs(ProjectReference project,List<AssetReference> references)throws Exception {
|
||||
var banks=catalog.list(project,false);var revisions=AssetWorkspaceFiles.inputs(project.rootPath());var result=new TreeMap<String,String>();
|
||||
for(var reference:references) {
|
||||
var bank=banks.stream().filter(a->a.reference().equals(reference)).findFirst().orElseThrow(()->new IllegalArgumentException("Unknown ownership dependency: "+reference.value()));
|
||||
String prefix=project.rootPath().relativize(bank.root())+"/";
|
||||
revisions.forEach((path,hash)->{if(path.startsWith(prefix))result.put(path,hash);});
|
||||
}return result;
|
||||
}
|
||||
List<Ownership> list(ProjectReference project)throws Exception {
|
||||
var result=new ArrayList<Ownership>();for(var record:records(project)) {
|
||||
var value=record.ownership();Path output=AssetWorkspaceFiles.path(project.rootPath(),value.outputPath());
|
||||
boolean missingDependency=false;Map<String,String> current;try{current=inputs(project,value.dependencies());}catch(IllegalArgumentException missing){missingDependency=true;current=Map.of();}
|
||||
boolean stale=value.stale()||missingDependency||!record.dependencyInputs().equals(current)
|
||||
||!Files.isRegularFile(output)||!Objects.equals(record.outputHash(),AssetWorkspaceFiles.hash(Files.readAllBytes(output)));
|
||||
result.add(new Ownership(value.owner(),value.outputPath(),value.producer(),value.dependencies(),stale));
|
||||
}return result;
|
||||
}
|
||||
void update(ProjectReference project,List<Ownership> declarations)throws Exception {
|
||||
if(declarations.isEmpty())return;
|
||||
var records=new LinkedHashMap<String,Record>();records(project).forEach(r->records.put(r.ownership().outputPath(),r));
|
||||
var banks=catalog.list(project,false);
|
||||
for(var requested:declarations) {
|
||||
var declaration=new Ownership(resolve(project,requested.owner()),requested.outputPath(),requested.producer(),requested.dependencies().stream().map(r->resolve(project,r)).toList(),requested.stale());
|
||||
Path output=AssetWorkspaceFiles.path(project.rootPath(),declaration.outputPath());
|
||||
if(!Files.isRegularFile(output))throw new IllegalArgumentException("Declared generated output does not exist: "+declaration.outputPath());
|
||||
var dependencies=inputs(project,declaration.dependencies());String hash=AssetWorkspaceFiles.hash(Files.readAllBytes(output));
|
||||
var prior=records.get(declaration.outputPath());
|
||||
if(prior!=null&&Objects.equals(prior.outputHash(),hash)&&!prior.dependencyInputs().equals(dependencies))dependencies=prior.dependencyInputs();
|
||||
records.put(declaration.outputPath(),new Record(declaration,dependencies,hash));
|
||||
}
|
||||
AssetWorkspaceFiles.write(json,AssetWorkspaceFiles.path(project.rootPath(),AssetWorkspaceFiles.OWNERSHIP),records.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.app.evidence.PngEvidenceCodec;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Exact human-selected external source grants. Agent supplied strings cannot create grants. */
|
||||
final class AssetPngSources {
|
||||
record Grant(Path project,Path source,AuthorizedPng value){}
|
||||
private final Map<String,Grant> grants=new ConcurrentHashMap<>();
|
||||
private final PngEvidenceCodec png=new PngEvidenceCodec();
|
||||
AuthorizedPng authorize(Path root,Path source)throws Exception {
|
||||
Path canonical=source.toRealPath();byte[] bytes=read(canonical);var pixels=png.decode(bytes);
|
||||
var value=new AuthorizedPng(UUID.randomUUID().toString(),AssetWorkspaceFiles.hash(bytes),bytes.length,pixels.width(),pixels.height());
|
||||
grants.put(value.grantId(),new Grant(root.toRealPath(),canonical,value));return value;
|
||||
}
|
||||
Path resolve(Path root,PngInput input)throws Exception {
|
||||
if(input.projectRelativePath()!=null)return AssetWorkspaceFiles.path(root,input.projectRelativePath());
|
||||
Grant grant=grants.get(input.externalGrantId());
|
||||
if(grant==null||!grant.project().equals(root.toRealPath()))throw new IllegalArgumentException("PNG source has no matching project-bound human grant");
|
||||
if(!grant.source().toRealPath().equals(grant.source()))throw new IllegalArgumentException("Selected PNG source was redirected");
|
||||
return grant.source();
|
||||
}
|
||||
byte[] bytes(Path root,PngInput input)throws Exception {
|
||||
byte[] bytes=read(resolve(root,input));png.decode(bytes);
|
||||
if(!AssetWorkspaceFiles.hash(bytes).equals(input.sha256()))throw new IllegalArgumentException("PNG source bytes changed");
|
||||
return bytes;
|
||||
}
|
||||
private static byte[] read(Path path)throws Exception {
|
||||
if(!Files.isRegularFile(path)||Files.size(path)>32*1024*1024)throw new IllegalArgumentException("PNG source must be a bounded regular file");
|
||||
try(var stream=Files.newInputStream(path)) {
|
||||
byte[] bytes=stream.readNBytes(32*1024*1024+1);
|
||||
if(bytes.length>32*1024*1024)throw new IllegalArgumentException("PNG source exceeds 32 MiB");return bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/** Revision/staging over the actual project inputs, excluding derived packer caches. */
|
||||
final class AssetWorkspaceFiles {
|
||||
static final String OWNERSHIP=".studio/asset-ownership.json";
|
||||
static final List<String> REQUIRED=List.of("prometeu.json","assets/.prometeu/index.json",OWNERSHIP);
|
||||
static String hash(byte[] data) {
|
||||
try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data));}
|
||||
catch(java.security.NoSuchAlgorithmException impossible){throw new AssertionError(impossible);}
|
||||
}
|
||||
static Path path(Path root,String relative)throws Exception {
|
||||
Path normalized=root.toAbsolutePath().normalize(),result=normalized.resolve(relative).normalize();
|
||||
if(!result.startsWith(normalized)||result.equals(normalized))throw new IllegalArgumentException("Asset path escapes project");
|
||||
Path part=normalized;for(Path element:normalized.relativize(result)){part=part.resolve(element);if(Files.isSymbolicLink(part))throw new IllegalArgumentException("Asset path contains a symbolic link: "+relative);}
|
||||
return result;
|
||||
}
|
||||
static SortedMap<String,String> inputs(Path root)throws Exception {
|
||||
var inputs=new TreeMap<String,String>();Path assets=path(root,"assets");
|
||||
if(Files.exists(assets))try(var files=Files.walk(assets)) {
|
||||
for(Path file:files.toList()) {
|
||||
if(Files.isSymbolicLink(file))throw new IllegalArgumentException("Asset symlink is not a transactional input: "+file);
|
||||
String relative=root.relativize(file).toString();
|
||||
if(Files.isRegularFile(file)&&!relative.equals("assets/.prometeu/cache.json")&&!file.getFileName().toString().startsWith(".asset-publish-"))inputs.put(relative,hash(Files.readAllBytes(file)));
|
||||
}
|
||||
}
|
||||
for(String relative:REQUIRED){Path file=path(root,relative);if(Files.isRegularFile(file))inputs.put(relative,hash(Files.readAllBytes(file)));}
|
||||
return inputs;
|
||||
}
|
||||
static Revision revision(Path root)throws Exception {
|
||||
var inputs=inputs(root);var absent=new TreeSet<String>(REQUIRED);absent.removeAll(inputs.keySet());
|
||||
StringBuilder canonical=new StringBuilder("asset-revision:1\n");inputs.forEach((p,h)->canonical.append(p).append('\0').append(h).append('\n'));
|
||||
absent.forEach(p->canonical.append(p).append("\0absent\n"));
|
||||
return new Revision(1,hash(canonical.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)),inputs,absent);
|
||||
}
|
||||
static void copy(Path from,Path to)throws Exception {
|
||||
Files.createDirectories(to);
|
||||
for(String relative:inputs(from).keySet()){Path target=path(to,relative);Files.createDirectories(target.getParent());Files.copy(path(from,relative),target,StandardCopyOption.REPLACE_EXISTING);}
|
||||
}
|
||||
static List<FileChange> changes(Path before,Path after,ObjectMapper json)throws Exception {
|
||||
var a=inputs(before);var b=inputs(after);var paths=new TreeSet<>(a.keySet());paths.addAll(b.keySet());var result=new ArrayList<FileChange>();
|
||||
for(String relative:paths) {
|
||||
String old=a.get(relative),next=b.get(relative);if(Objects.equals(old,next))continue;
|
||||
if(old!=null&&next!=null&&relative.endsWith(".json")) {
|
||||
var left=json.readTree(path(before,relative).toFile());var right=json.readTree(path(after,relative).toFile());
|
||||
if(Objects.equals(left,right)){Files.copy(path(before,relative),path(after,relative),StandardCopyOption.REPLACE_EXISTING);continue;}
|
||||
}
|
||||
result.add(new FileChange(relative,old==null?FileAction.create:next==null?FileAction.delete:FileAction.replace,old,next));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static List<Conflict> conflicts(Revision expected,Revision actual) {
|
||||
var paths=new TreeSet<>(expected.inputSha256().keySet());paths.addAll(actual.inputSha256().keySet());
|
||||
var conflicts=new ArrayList<Conflict>();for(String p:paths)if(!Objects.equals(expected.inputSha256().get(p),actual.inputSha256().get(p)))
|
||||
conflicts.add(new Conflict(p,expected.inputSha256().get(p),actual.inputSha256().get(p),"Project input changed since preview"));
|
||||
if(conflicts.isEmpty()&&!expected.equals(actual))conflicts.add(new Conflict("prometeu.json",expected.inputSha256().get("prometeu.json"),actual.inputSha256().get("prometeu.json"),"Revision identity mismatch; obtain a fresh canonical project revision"));
|
||||
return conflicts;
|
||||
}
|
||||
static void write(ObjectMapper json,Path path,Object value)throws Exception {
|
||||
Files.createDirectories(path.getParent());Path temporary=Files.createTempFile(path.getParent(),".record-",".tmp");
|
||||
try{Files.write(temporary,json.writeValueAsBytes(value));Files.move(temporary,path,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}finally{Files.deleteIfExists(temporary);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.packer.messages.PackerProjectContext;
|
||||
import p.packer.messages.PublishWorkspaceFilesRequest;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.core.assets.*;
|
||||
import p.studio.core.assets.metadata.AssetStudioMetadataService;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Durable request correlation over the packer's shared transactional project boundary. */
|
||||
public final class FileAssetBatchWorkspace implements AssetBatchWorkspace {
|
||||
record Scope(String task,String request,Request parameters){}
|
||||
record Commit(String task,String request,String batch,Revision expected){}
|
||||
private final ObjectMapper json;private final PackerWorkspaceService packer;
|
||||
private final AssetCatalog catalog;private final AssetPngSources sources=new AssetPngSources();
|
||||
private final Function<ProjectReference,AssetBudgets.Snapshot> budgets;
|
||||
public FileAssetBatchWorkspace(ObjectMapper mapper,PackerWorkspaceService packer,Function<ProjectReference,AssetBudgets.Snapshot> budgets) {
|
||||
this.json=AssetBatchJson.mapper(mapper);this.packer=packer;this.catalog=new PackerAssetCatalog(packer);this.budgets=budgets;
|
||||
}
|
||||
private PackerProjectContext context(ProjectReference p){return new PackerProjectContext(p.name(),p.rootPath());}
|
||||
private <T>T exclusive(ProjectReference p,Callable<T> work){return packer.withProject(context(p),work);}
|
||||
private Path home(ProjectReference p)throws Exception{return AssetWorkspaceFiles.path(p.rootPath(),".studio/asset-batches");}
|
||||
private Path batch(ProjectReference p,String id)throws Exception{UUID.fromString(id);return AssetWorkspaceFiles.path(p.rootPath(),".studio/asset-batches/"+id);}
|
||||
private List<Path> batches(ProjectReference p)throws Exception {
|
||||
Path home=home(p);if(!Files.exists(home))return List.of();
|
||||
try(var dirs=Files.list(home)){return dirs.filter(d->{if(Files.isSymbolicLink(d))throw new IllegalArgumentException("Batch directory cannot be a symbolic link");return Files.isDirectory(d);}).filter(d->d.getFileName().toString().matches("[0-9a-f-]{36}")).sorted().toList();}
|
||||
}
|
||||
private <T>T read(Path path,Class<T> type)throws Exception {if(Files.isSymbolicLink(path)||!Files.isRegularFile(path))throw new IllegalArgumentException("Batch record not found or unsafe");return json.readValue(path.toFile(),type);}
|
||||
@Override public List<AssetSummary> catalog(ProjectReference p){return exclusive(p,()->catalog.list(p,false));}
|
||||
@Override public List<ArtifactInfo> artifacts(ProjectReference p,AssetReference reference){return exclusive(p,()->{
|
||||
var asset=catalog.list(p,false).stream().filter(a->a.reference().equals(reference)||reference.isAssetRootReference()&&p.rootPath().resolve("assets").resolve(reference.rawValue()).normalize().equals(a.root())).findFirst().orElseThrow(()->new IllegalArgumentException("Unknown glyph bank"));
|
||||
if(asset.family()!=AssetFamily.GLYPH_BANK)throw new IllegalArgumentException("Artifact catalog requires a glyph bank");
|
||||
var layout=packer.getGlyphBankLayout(new p.packer.messages.GetGlyphBankLayoutRequest(context(p),UUID.fromString(asset.assetUuid())));
|
||||
return layout.glyphs().stream().map(g->new ArtifactInfo(new Artifact(asset.reference(),g.artifactId()),g.glyphId(),g.fingerprint(),g.imagePath().toString(),g.width(),g.height())).toList();
|
||||
});}
|
||||
@Override public Revision revision(ProjectReference p){return exclusive(p,()->AssetWorkspaceFiles.revision(p.rootPath()));}
|
||||
@Override public AssetDetailsSnapshot inspect(ProjectReference p,AssetReference bank){return exclusive(p,()->new PackerAssetDetails(packer,false).get(p,bank));}
|
||||
@Override public List<ArtifactInfo> previewArtifacts(ProjectReference p,String id,AssetReference bank){return exclusive(p,()->{
|
||||
Path root=batch(p,id).resolve("candidate");read(batch(p,id).resolve("preview.json"),Preview.class);
|
||||
return artifacts(new ProjectReference(p.name(),p.version(),p.languageId(),p.stdlibVersion(),p.target(),root,p.appId(),p.memcardSlots()),bank);
|
||||
});}
|
||||
@Override public List<Ownership> dependencies(ProjectReference p,AssetReference asset){return exclusive(p,()->{var graph=new AssetOwnershipGraph(json,catalog);var reference=graph.resolve(p,asset);return graph.list(p).stream().filter(o->o.owner().equals(reference)||o.dependencies().contains(reference)).toList();});}
|
||||
@Override public AssetBudgets.Snapshot budget(ProjectReference p){return exclusive(p,()->budgets.apply(p));}
|
||||
@Override public AuthorizedPng authorize(ProjectReference p,Path source){return exclusive(p,()->sources.authorize(p.rootPath(),source));}
|
||||
@Override public Preview preview(ProjectReference p,String task,String id){return exclusive(p,()->read(batch(p,id).resolve("preview.json"),Preview.class));}
|
||||
@Override public Preview preview(ProjectReference p,String task,String request,Request changes) {
|
||||
return exclusive(p,()->{
|
||||
for(Path directory:batches(p))if(Files.exists(directory.resolve("scope.json"))) {
|
||||
var scope=read(directory.resolve("scope.json"),Scope.class);
|
||||
if(Objects.equals(scope.task(),task)&&scope.request().equals(request)) {
|
||||
if(!scope.parameters().equals(changes))throw conflict("Preview request parameters changed");
|
||||
return read(directory.resolve("preview.json"),Preview.class);
|
||||
}
|
||||
}
|
||||
String id=UUID.randomUUID().toString();Path directory=batch(p,id);Files.createDirectories(directory);
|
||||
var actual=AssetWorkspaceFiles.revision(p.rootPath());var conflicts=AssetWorkspaceFiles.conflicts(changes.expectedRevision(),actual);
|
||||
var diagnostics=new ArrayList<Diagnostic>();var affected=List.<ReferenceUse>of();var files=List.<FileChange>of();var assets=List.<AssetReference>of();var ownership=List.<Ownership>of();
|
||||
PreviewState state=PreviewState.conflict;
|
||||
if(conflicts.isEmpty()) {
|
||||
Path stageRoot=directory.resolve("candidate");AssetWorkspaceFiles.copy(p.rootPath(),stageRoot);
|
||||
var stage=new ProjectReference(p.name(),p.version(),p.languageId(),p.stdlibVersion(),p.target(),stageRoot,p.appId(),p.memcardSlots());
|
||||
var stagedCatalog=new PackerAssetCatalog(packer);var stagedMetadata=new AssetStudioMetadataService(json);
|
||||
var stagedCommands=new PackerAssetCommands(packer,path->{if(!path.toAbsolutePath().normalize().equals(stageRoot))throw new IllegalArgumentException("Staged asset command escaped its workspace");return ()->{};});
|
||||
var edits=new AssetBatchMutations(stagedCommands,stagedCatalog,stagedMetadata,json,sources,packer);
|
||||
try {
|
||||
for(var mutation:changes.mutations()) {
|
||||
if(Thread.currentThread().isInterrupted())throw new java.util.concurrent.CancellationException("Cancelled asset preview");
|
||||
edits.apply(p,stage,mutation);
|
||||
}
|
||||
var references=new AssetBatchReferences(stagedCatalog,stagedMetadata,packer,json);
|
||||
affected=references.apply(p,stage,changes.rebinds());
|
||||
if(!affected.isEmpty())diagnostics.add(diagnostic("REFERENCE_REBIND_REQUIRED","Explicit rebind is required for affected references",affected));
|
||||
var graph=new AssetOwnershipGraph(json,stagedCatalog);graph.update(stage,changes.ownership());ownership=graph.list(stage);
|
||||
// Asset drafts may coexist with other unfinished banks. Cartridge validation
|
||||
// still sees the original blocking producer fact for every included bank.
|
||||
var candidateChanges=AssetWorkspaceFiles.changes(p.rootPath(),stageRoot,json);
|
||||
var validation=packer.validatePackWorkspace(new p.packer.messages.ValidatePackWorkspaceRequest(context(stage)));
|
||||
for(var asset:validation.assets())for(var diagnostic:asset.diagnostics())if(diagnostic.blocking()) {
|
||||
var fact=AssetBatchDiagnostics.from(diagnostic,stageRoot,p.rootPath());
|
||||
boolean changed=candidateChanges.stream().anyMatch(file->stageRoot.resolve(file.path()).startsWith(asset.assetPath()));
|
||||
if(!changed||"SCENE_REQUEST_MISSING".equals(fact.code())) {
|
||||
var details=new LinkedHashMap<>(fact.context());details.put("cartridgeBlocking",true);details.put("publicationScope","asset_draft");
|
||||
fact=new Diagnostic(fact.producer(),fact.code(),fact.severity(),fact.message(),false,fact.assetRoot(),fact.path(),fact.family(),fact.missingIndices(),fact.duplicateIndices(),fact.references(),fact.used(),fact.required(),fact.limit(),details);
|
||||
}
|
||||
diagnostics.add(fact);
|
||||
}
|
||||
}catch(java.util.concurrent.CancellationException stop){throw stop;}
|
||||
catch(Exception invalid){diagnostics.add(diagnostic("ASSET_MUTATION_REJECTED",Objects.requireNonNullElse(invalid.getMessage(),invalid.getClass().getSimpleName()),List.of()));}
|
||||
files=AssetWorkspaceFiles.changes(p.rootPath(),stageRoot,json);
|
||||
var changedFiles=files;
|
||||
assets=stagedCatalog.list(stage,false).stream().filter(asset->changedFiles.stream().anyMatch(file->stageRoot.resolve(file.path()).startsWith(asset.root()))).map(AssetSummary::reference).toList();
|
||||
conflicts=AssetWorkspaceFiles.conflicts(actual,AssetWorkspaceFiles.revision(p.rootPath()));
|
||||
state=!conflicts.isEmpty()?PreviewState.conflict:diagnostics.stream().anyMatch(Diagnostic::blocking)?PreviewState.rejected:files.isEmpty()?PreviewState.no_op:PreviewState.ready;
|
||||
}
|
||||
var preview=new Preview(id,request,changes.expectedRevision(),changes,state,files,assets,affected,ownership,conflicts,diagnostics);
|
||||
AssetWorkspaceFiles.write(json,directory.resolve("preview.json"),preview);
|
||||
AssetWorkspaceFiles.write(json,directory.resolve("scope.json"),new Scope(task,request,changes));return preview;
|
||||
});
|
||||
}
|
||||
@Override public Result commit(ProjectReference p,String task,String request,String id,Revision expected) {
|
||||
return exclusive(p,()->{
|
||||
Commit parameters=new Commit(task,request,id,expected);
|
||||
for(Path directory:batches(p))if(Files.exists(directory.resolve("commit-request.json"))) {
|
||||
var prior=read(directory.resolve("commit-request.json"),Commit.class);
|
||||
if(Objects.equals(prior.task(),task)&&prior.request().equals(request)) {
|
||||
if(!prior.equals(parameters))throw conflict("Commit request parameters changed");
|
||||
if(Files.exists(directory.resolve("result.json")))return resultInLane(p,directory.getFileName().toString());
|
||||
}
|
||||
}
|
||||
Path directory=batch(p,id);var scope=read(directory.resolve("scope.json"),Scope.class);
|
||||
if(!Objects.equals(scope.task(),task))throw new IllegalArgumentException("Commit requires the preview's current task authority");
|
||||
var preview=read(directory.resolve("preview.json"),Preview.class);
|
||||
if(Files.exists(directory.resolve("result.json")))throw conflict("Batch already has a different commit request");
|
||||
if(!expected.equals(preview.revision()))throw conflict("Commit revision does not match the reviewed preview");
|
||||
AssetWorkspaceFiles.write(json,directory.resolve("commit-request.json"),parameters);
|
||||
var before=AssetWorkspaceFiles.revision(p.rootPath());var conflicts=AssetWorkspaceFiles.conflicts(expected,before);
|
||||
var diagnostics=new ArrayList<>(preview.diagnostics());
|
||||
try{for(var mutation:preview.request().mutations())if(mutation instanceof ImportPng png)sources.bytes(p.rootPath(),png.source());}
|
||||
catch(Exception changed){diagnostics.add(diagnostic("PNG_SOURCE_CHANGED",Objects.requireNonNullElse(changed.getMessage(),"Source no longer authorized"),List.of()));}
|
||||
CommitState state=!conflicts.isEmpty()?CommitState.conflict:!preview.canCommit()||diagnostics.stream().anyMatch(Diagnostic::blocking)?CommitState.rejected:preview.files().isEmpty()?CommitState.no_op:CommitState.committed;
|
||||
if(Thread.currentThread().isInterrupted())state=CommitState.cancelled;
|
||||
if(state!=CommitState.committed) {
|
||||
var result=new Result(id,request,state,before,before,List.of(),preview.assets(),conflicts,diagnostics);
|
||||
boolean stop=Thread.interrupted();try{AssetWorkspaceFiles.write(json,directory.resolve("result.json"),result);}finally{if(stop)Thread.currentThread().interrupt();}return result;
|
||||
}
|
||||
Path candidate=directory.resolve("candidate");
|
||||
var current=AssetWorkspaceFiles.inputs(candidate);
|
||||
var reviewed=new java.util.TreeMap<>(expected.inputSha256());
|
||||
for(var file:preview.files())if(file.afterSha256()==null)reviewed.remove(file.path());else reviewed.put(file.path(),file.afterSha256());
|
||||
if(!reviewed.equals(current))throw new IllegalStateException("Staged candidate differs from the reviewed file set");
|
||||
for(var file:preview.files())if(!Objects.equals(current.get(file.path()),file.afterSha256()))throw new IllegalStateException("Staged candidate was modified after preview");
|
||||
var after=AssetWorkspaceFiles.revision(candidate);var result=new Result(id,request,state,before,after,preview.files(),preview.assets(),List.of(),diagnostics);
|
||||
var publication=new ArrayList<PublishWorkspaceFilesRequest.Edit>();
|
||||
for(var file:preview.files())publication.add(new PublishWorkspaceFilesRequest.Edit(file.path(),file.beforeSha256(),file.afterSha256()==null?null:Files.readAllBytes(AssetWorkspaceFiles.path(candidate,file.path()))));
|
||||
publication.add(new PublishWorkspaceFilesRequest.Edit(p.rootPath().relativize(directory.resolve("result.json")).toString(),null,json.writeValueAsBytes(result)));
|
||||
packer.publishWorkspaceFiles(new PublishWorkspaceFilesRequest(context(p),id,publication));return result;
|
||||
});
|
||||
}
|
||||
@Override public Result result(ProjectReference p,String task,String id){return exclusive(p,()->resultInLane(p,id));}
|
||||
private Result resultInLane(ProjectReference p,String id)throws Exception {
|
||||
var result=read(batch(p,id).resolve("result.json"),Result.class);
|
||||
if(result.applied()&&Files.exists(AssetWorkspaceFiles.path(p.rootPath(),".studio/asset-transactions/"+id+"/recovered")))
|
||||
return new Result(result.batchId(),result.requestId(),CommitState.recovered,result.before(),result.after(),result.files(),result.assets(),result.conflicts(),result.diagnostics());
|
||||
return result;
|
||||
}
|
||||
private static AutomationException conflict(String message){return new AutomationException(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,message);}
|
||||
private static Diagnostic diagnostic(String code,String message,List<ReferenceUse> references){return new Diagnostic("studio",code,"ERROR",message,true,null,null,null,List.of(),List.of(),references,null,null,null,Map.of());}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import p.studio.api.assets.AssetBudgets;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import java.nio.*;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Same admission for headless and desktop: verify qualification, actual cartridge bytes and serialized preload. */
|
||||
public final class ManagedAssetGuard {
|
||||
private final ObjectMapper json;private final AssetCapacityProfiles profiles;
|
||||
public ManagedAssetGuard(ObjectMapper json){this.json=json;profiles=new AssetCapacityProfiles(json);}
|
||||
public Map<String,Object> require(Path project,Path cartridge,ProjectLocalStudioSetup setup)throws Exception {
|
||||
var selected=profiles.select(setup);
|
||||
if(selected.state()!=AssetBudgets.QualificationState.known)throw failure("ASSET_PROFILE_UNKNOWN",selected.reason());
|
||||
Path root=cartridge.toRealPath();if(!root.startsWith(project.toRealPath()))throw failure("BUILD_OUTSIDE_PROJECT","Cartridge is outside its project");
|
||||
Path file=AssetWorkspaceFiles.path(root,"asset-capacity.json");
|
||||
if(!Files.isRegularFile(file)||Files.size(file)>32*1024*1024)throw failure("ASSET_BUILD_UNQUALIFIED","Rebuild with a compatible selected runtime before managed execution");
|
||||
var record=json.readTree(file.toFile());var qualification=record.path("snapshot").path("qualification");var profile=qualification.path("profile");
|
||||
if(record.path("contractVersion").asInt()!=1||!qualification.path("state").asText().equals("known")
|
||||
||!profile.path("profileId").asText().equals(selected.profile().profileId())
|
||||
||!profile.path("executableSha256").asText().equals(selected.selectedExecutableSha256()))
|
||||
throw failure("ASSET_BUILD_PROFILE_CHANGED","Build capacity qualification does not match the selected runtime; rebuild required");
|
||||
if (!profile.equals(json.valueToTree(selected.profile())))
|
||||
throw failure("ASSET_BUILD_PROFILE_CHANGED", "Build capacity evidence changed; rebuild required");
|
||||
if(!record.path("snapshot").path("revision").equals(json.valueToTree(AssetWorkspaceFiles.revision(project))))
|
||||
throw failure("ASSET_BUILD_INPUTS_CHANGED", "Asset inputs changed since qualification; rebuild required");
|
||||
var hashes=record.path("files");
|
||||
for(String name:List.of("manifest.json","program.pbx","assets.pa","asset_table.json","preload.json")) {
|
||||
Path input=AssetWorkspaceFiles.path(root,name);
|
||||
if(!Files.isRegularFile(input)||!AssetWorkspaceFiles.hash(Files.readAllBytes(input)).equals(hashes.path(name).asText()))
|
||||
throw failure("ASSET_BUILD_BYTES_CHANGED","Qualified cartridge bytes changed: "+name);
|
||||
}
|
||||
JsonNode packed=header(root.resolve("assets.pa"));var banks=new HashMap<Integer,String>();
|
||||
for(var bank:packed.path("asset_table")) {
|
||||
int id=integer(bank.path("asset_id"));String type=bank.path("bank_type").asText();
|
||||
if(banks.put(id,type)!=null)throw failure("ASSET_TOPOLOGY_INVALID","Duplicate cold AssetId");
|
||||
}
|
||||
var claimed=new HashSet<String>();var required=new TreeMap<String,Integer>();
|
||||
for(var preload:packed.path("preload")) {
|
||||
int id=integer(preload.path("asset_id")),slot=integer(preload.path("slot"));String type=banks.get(id);
|
||||
if(type==null||!claimed.add(type+":"+slot))throw failure("ASSET_TOPOLOGY_INVALID","Unknown preload bank or duplicate runtime slot");
|
||||
Integer limit=null;for(var entry:selected.profile().limits().entrySet())if(entry.getKey().runtimeTag().equals(type))limit=entry.getValue();
|
||||
if(limit==null||slot>=limit)throw new AutomationException(new AutomationFailure(AutomationFailure.Code.LIMIT_EXCEEDED,"Managed preload is outside the qualified capacity",Map.of(),
|
||||
p.studio.api.values.ValueMaps.fields("code","PRELOAD_CAPACITY_EXCEEDED","bankType",type,"slot",slot,"assetId",id,"limit",limit,"profileId",selected.profile().profileId())));
|
||||
required.merge(type,slot+1,Math::max);
|
||||
}
|
||||
return Map.of("profileId",selected.profile().profileId(),"selectedExecutableSha256",selected.selectedExecutableSha256(),"requiredSlots",required,"inputRevision",record.path("snapshot").path("revision").path("sha256").asText());
|
||||
}
|
||||
private JsonNode header(Path path)throws Exception {
|
||||
try(var file=FileChannel.open(path,StandardOpenOption.READ)) {
|
||||
var prelude=ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN);read(file,prelude);prelude.flip();
|
||||
if(prelude.get()!='A'||prelude.get()!='S'||prelude.get()!='P'||prelude.get()!='A'||prelude.getInt()!=1)throw failure("ASSET_HEADER_INVALID","Unsupported packed asset header");
|
||||
int size=prelude.getInt();long payload=prelude.getLong();
|
||||
if(size<2||size>32*1024*1024||payload!=32L+size||payload>file.size())throw failure("ASSET_HEADER_INVALID","Invalid packed asset header bounds");
|
||||
var bytes=ByteBuffer.allocate(size);read(file,bytes);var header=json.readTree(bytes.array());
|
||||
if(!header.path("asset_table").isArray()||!header.path("preload").isArray())throw failure("ASSET_HEADER_INVALID","Expected asset table and preload arrays");
|
||||
return header;
|
||||
}
|
||||
}
|
||||
private static void read(FileChannel source,ByteBuffer target)throws Exception{while(target.hasRemaining())if(source.read(target)<0)throw new java.io.EOFException("Truncated assets.pa header");}
|
||||
private static int integer(JsonNode node){if(!node.isIntegralNumber()||!node.canConvertToInt()||node.intValue()<0)throw failure("ASSET_TOPOLOGY_INVALID","Expected a nonnegative lossless cold ID or slot");return node.intValue();}
|
||||
private static AutomationException failure(String code,String message){return new AutomationException(new AutomationFailure(AutomationFailure.Code.RUNTIME_INCOMPATIBLE,message,Map.of(),Map.of("code",code)));}
|
||||
}
|
||||
@@ -24,7 +24,12 @@ public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway {
|
||||
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());
|
||||
return compile(project, p.studio.api.automation.BuildSelection.productionBuild(), project.rootPath().resolve("build"), logSink);
|
||||
}
|
||||
@Override public CompilerBuildOutput compile(ProjectReference project, p.studio.api.automation.BuildSelection selection,
|
||||
java.nio.file.Path outputDirectory, Consumer<String> logSink) {
|
||||
final var config = new BuilderPipelineConfig(false, project.rootPath().toString(), "core-v1",
|
||||
p.studio.compiler.utilities.SourceProviderFactory.filesystem(), selection.targetId(), outputDirectory);
|
||||
var context=BuilderPipelineContext.fromConfig(config);context.glyphBankLayoutSource=layouts;
|
||||
var analysisId = UUID.randomUUID().toString();
|
||||
try {
|
||||
@@ -53,14 +58,24 @@ public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway {
|
||||
private Map<String, Object> inputContext(BuilderPipelineContext context, java.nio.file.Path root, String analysisId,
|
||||
Map<Integer, SourceReference> sources) {
|
||||
var workspace = context.resolvedWorkspace;
|
||||
return ImmutableJson.fields("projectRoot", root.toString(), "analysisId", analysisId,
|
||||
var sourceHashes = new java.util.TreeMap<String, String>();
|
||||
var diskHashes = new java.util.TreeMap<String, String>();
|
||||
var configurationHashes = new java.util.TreeMap<String, String>();
|
||||
if (workspace != null) for (var descriptor : workspace.graph().projectTable().values())
|
||||
if (descriptor.getManifestSha256() != null) configurationHashes.put(descriptor.getRootPath().resolve("prometeu.json").toString(), descriptor.getManifestSha256());
|
||||
sources.values().forEach(source -> { if (source.sha256() != null && !source.mixedRevisions()) sourceHashes.put(source.canonicalPath(), source.sha256()); });
|
||||
sourceHashes.forEach((path, hash) -> { if (java.nio.file.Files.isRegularFile(java.nio.file.Path.of(path))) diskHashes.put(path, hash); });
|
||||
var limitations = new java.util.ArrayList<Map<String, Object>>();
|
||||
limitations.add(ImmutableJson.fields("code", "PACK_INPUT_REVISIONS_NOT_CAPTURED", "message", "Compiler source revisions do not identify all pack/assets inputs"));
|
||||
if (configurationHashes.isEmpty()) limitations.add(ImmutableJson.fields("code", "CONFIGURATION_REVISION_NOT_RECORDED", "message", "Configuration values are recorded without a manifest-byte revision"));
|
||||
return ImmutableJson.fields("projectRoot", root.toString(), "analysisId", analysisId, "targetId", context.config.buildTargetId(),
|
||||
"sourceSha256", sourceHashes, "diskSourceSha256", diskHashes, "configurationSha256", configurationHashes,
|
||||
"entrypoint", workspace == null || workspace.mainProject().getEntrypoint() == null ? null : workspace.mainProject().getEntrypoint().toString(),
|
||||
"taskId", null, "operationId", null, "clientRequestId", null, "buildId", null, "queryId", null, "document", null,
|
||||
"inputs", CompilerDiagnosticProjection.inputs(sources, root), "inputCoverage", "compiler-inputs",
|
||||
"configuration", ImmutableJson.fields("languageId", workspace == null || workspace.frontendSpec() == null ? null : workspace.frontendSpec().getLanguageId(),
|
||||
"sdkVersion", workspace == null ? null : workspace.stdlib(), "target", workspace == null ? null : workspace.target().name(),
|
||||
"vmProfile", context.config.vmProfile(), "revisionAvailability", "not-recorded"),
|
||||
"coverage", "partial", "limitations", java.util.List.of(ImmutableJson.fields("code", "PACK_INPUT_REVISIONS_NOT_CAPTURED",
|
||||
"message", "Compiler source revisions do not identify all pack/assets inputs"),
|
||||
ImmutableJson.fields("code", "CONFIGURATION_REVISION_NOT_RECORDED", "message", "Configuration values are recorded without a manifest-byte revision")));
|
||||
"vmProfile", context.config.vmProfile(), "revisionAvailability", configurationHashes.isEmpty() ? "not-recorded" : "recorded"),
|
||||
"coverage", "partial", "limitations", limitations);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,8 +165,11 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge {
|
||||
return new Reference(ref.id(), ref.title(), owned.owner(), ReferenceKind.valueOf(ref.kind().name()),
|
||||
new Version(ref.version(), ref.versionSource()));
|
||||
}).toList();
|
||||
var automation = openProjects.findAutomation(root).map(p.studio.api.automation.AutomationSession::snapshot).orElse(null);
|
||||
if (automation == null) limitations.add("Automation state is unavailable in this project context");
|
||||
return new Discovery(new Context(root, discovered.get(root).name(), languages, libraries,
|
||||
List.of(root), List.copyOf(readOnly), descriptors, limitations.stream().distinct().toList()), Map.copyOf(references));
|
||||
List.of(root), List.copyOf(readOnly), descriptors, limitations.stream().distinct().toList(),
|
||||
automation == null ? null : automation.controlObservation(), automation == null ? null : automation.runtimeObservation()), Map.copyOf(references));
|
||||
}
|
||||
|
||||
private Language language(String id, List<ProjectReference> projects, boolean primary,
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package p.studio.app.evidence;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.*;
|
||||
import java.nio.file.*;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Immutable transaction directories; the atomic directory move is the only publication point. */
|
||||
public final class FileEvidenceStore implements EvidenceStore {
|
||||
private static final Map<Path,Object> MONITORS=new ConcurrentHashMap<>();
|
||||
private record Grant(Path project,Path source) {}
|
||||
private final Map<String,Grant> grants=new ConcurrentHashMap<>();
|
||||
private final ObjectMapper mapper;
|
||||
private final long quota;
|
||||
public FileEvidenceStore(ObjectMapper mapper) {this(mapper,Long.getLong("prometeu.evidence.quotaBytes",Evidence.DEFAULT_QUOTA));}
|
||||
public FileEvidenceStore(ObjectMapper mapper,long quota) {
|
||||
if(quota<0)throw new IllegalArgumentException("Negative evidence quota");this.mapper=mapper;this.quota=quota;
|
||||
}
|
||||
public static String sha(byte[] bytes) {
|
||||
try {return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));}
|
||||
catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);}
|
||||
}
|
||||
private Path directory(Path root) throws IOException {
|
||||
Path canonical=root.toRealPath();Path studio=canonical.resolve(".studio");
|
||||
Files.createDirectories(studio);
|
||||
if(Files.isSymbolicLink(studio)||!studio.toRealPath().startsWith(canonical))throw denied("Studio state path escapes project");
|
||||
Path evidence=studio.resolve("evidence");Files.createDirectories(evidence);
|
||||
if(Files.isSymbolicLink(evidence)||!evidence.toRealPath().startsWith(canonical))throw denied("Evidence path escapes project");
|
||||
return evidence;
|
||||
}
|
||||
private <T>T locked(Path root,Work<T> work) {
|
||||
try {
|
||||
Path dir=directory(root);
|
||||
synchronized(MONITORS.computeIfAbsent(dir,k->new Object())) {
|
||||
Path lock=dir.resolve("store.lock");
|
||||
if(Files.isSymbolicLink(lock))throw denied("Invalid evidence lock");
|
||||
try(var channel=FileChannel.open(lock,StandardOpenOption.CREATE,StandardOpenOption.WRITE);var held=channel.lock()) {
|
||||
try(var entries=Files.list(dir)) {
|
||||
for(var stage:entries.filter(p->p.getFileName().toString().startsWith("staging-")).toList()) {
|
||||
if(Files.isSymbolicLink(stage)||!Files.isDirectory(stage))throw denied("Invalid evidence staging");
|
||||
removeStage(stage);
|
||||
}
|
||||
}
|
||||
return work.run(dir);
|
||||
}
|
||||
}
|
||||
} catch(IOException e){throw storage("Evidence storage unavailable",e);}
|
||||
}
|
||||
@FunctionalInterface private interface Work<T>{T run(Path directory)throws IOException;}
|
||||
public List<Evidence.Publication> list(Path root) {return locked(root,dir->scan(root,dir));}
|
||||
private List<Evidence.Publication> scan(Path root,Path dir)throws IOException {
|
||||
var result=new ArrayList<Evidence.Publication>();
|
||||
try(var entries=Files.list(dir)) {
|
||||
for(Path p:entries.filter(f->f.getFileName().toString().startsWith("pub-")).sorted().toList()) {
|
||||
if(Files.isSymbolicLink(p)||!Files.isDirectory(p))throw denied("Invalid evidence publication");
|
||||
var publication=mapper.readValue(boundedFile(p.resolve("publication.json"),4*1024*1024),Evidence.Publication.class);
|
||||
if(!publication.projectRoot().equals(root.toRealPath().toString())||!p.getFileName().toString().equals("pub-"+id(publication.id())))
|
||||
throw denied("Publication belongs to another project");
|
||||
result.add(publication);
|
||||
}
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
public Evidence.Publication publish(Path root,Evidence.Publication publication,List<Evidence.Blob> objects) {
|
||||
return locked(root,dir->{
|
||||
var all=scan(root,dir);
|
||||
for(var prior:all)if(prior.requestId().equals(publication.requestId())) {
|
||||
if(!prior.parameterKey().equals(publication.parameterKey()))throw new AutomationException(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,"Evidence request parameters changed");
|
||||
return prior;
|
||||
}
|
||||
if(!publication.projectRoot().equals(root.toRealPath().toString()))throw denied("Wrong evidence project");
|
||||
byte[] metadata=mapper.writeValueAsBytes(publication);long required=metadata.length;
|
||||
if(publication.artifacts().size()!=objects.size())throw new IllegalArgumentException("Incomplete publication");
|
||||
var ids=new HashSet<String>();
|
||||
for(var object:objects) {
|
||||
var artifact=object.artifact();var bytes=object.bytes();id(artifact.id());
|
||||
if(!ids.add(artifact.id())||!artifact.publicationId().equals(publication.id())||!publication.artifacts().contains(artifact)
|
||||
||artifact.byteSize()!=bytes.length||!artifact.sha256().equals(sha(bytes)))throw new IllegalArgumentException("Invalid evidence object");
|
||||
required=Math.addExact(required,bytes.length);
|
||||
}
|
||||
validateReferences(publication,all);
|
||||
long used=0;
|
||||
for(var p:all) {
|
||||
used=Math.addExact(used,Files.size(dir.resolve("pub-"+p.id()).resolve("publication.json")));
|
||||
for(var a:p.artifacts())used=Math.addExact(used,a.byteSize());
|
||||
}
|
||||
if(required>quota-used)throw new AutomationException(new AutomationFailure(AutomationFailure.Code.LIMIT_EXCEEDED,
|
||||
"Evidence quota exceeded",Map.of(),Map.of("used",used,"required",required,"limit",quota)));
|
||||
Path stage=Files.createTempDirectory(dir,"staging-");
|
||||
try {
|
||||
for(var object:objects)writeDurable(stage.resolve(id(object.artifact().id())+".png"),object.bytes());
|
||||
writeDurable(stage.resolve("publication.json"),metadata);
|
||||
if(Thread.currentThread().isInterrupted())throw new java.util.concurrent.CancellationException("Evidence publication cancelled");
|
||||
Files.move(stage,dir.resolve("pub-"+id(publication.id())),StandardCopyOption.ATOMIC_MOVE);
|
||||
return publication;
|
||||
} finally {if(Files.exists(stage))removeStage(stage);}
|
||||
});
|
||||
}
|
||||
private void validateReferences(Evidence.Publication p,List<Evidence.Publication> all) {
|
||||
var artifacts=new HashSet<String>();all.forEach(v->v.artifacts().forEach(a->artifacts.add(a.id())));p.artifacts().forEach(a->artifacts.add(a.id()));
|
||||
if(p.report()!=null&&(!artifacts.contains(p.report().expectedId())||!artifacts.contains(p.report().actualId())||!artifacts.contains(p.report().diffId())))throw missing();
|
||||
if(p.baseline()!=null) {
|
||||
if(!artifacts.contains(p.baseline().artifactId()))throw missing();
|
||||
// Creation timestamps, not UUID directory ordering, define revision order.
|
||||
String current=all.stream().filter(v->v.baseline()!=null).max(Comparator.comparing(Evidence.Publication::createdAt)).map(v->v.baseline().id()).orElse(null);
|
||||
if(!Objects.equals(current,p.baseline().previousRevision()))throw new AutomationException(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,"Baseline revision changed");
|
||||
}
|
||||
}
|
||||
private record Located(Evidence.Artifact artifact,Path file){}
|
||||
private Located locate(Path root,Path dir,String artifactId)throws IOException {
|
||||
id(artifactId);
|
||||
for(var p:scan(root,dir))for(var a:p.artifacts())if(a.id().equals(artifactId))return new Located(a,dir.resolve("pub-"+id(p.id())).resolve(artifactId+".png"));
|
||||
throw missing();
|
||||
}
|
||||
public Evidence.Read read(Path root,String artifactId,long offset,int length) {
|
||||
if(offset<0||length<0||length>Evidence.MAX_READ)throw new IllegalArgumentException("Invalid bounded evidence range");
|
||||
return locked(root,dir->{
|
||||
var item=locate(root,dir,artifactId);byte[] bytes=verified(item);
|
||||
if(offset>bytes.length||length>bytes.length-offset)throw new IllegalArgumentException("Evidence range exceeds object");
|
||||
return new Evidence.Read(artifactId,offset,bytes.length,Arrays.copyOfRange(bytes,(int)offset,(int)offset+length));
|
||||
});
|
||||
}
|
||||
public byte[] image(Path root,String artifactId) {return locked(root,dir->verified(locate(root,dir,artifactId)));}
|
||||
private byte[] verified(Located item)throws IOException {
|
||||
byte[] bytes=boundedFile(item.file,32*1024*1024);
|
||||
if(bytes.length!=item.artifact.byteSize()||!sha(bytes).equals(item.artifact.sha256()))throw storage("Evidence integrity check failed",null);
|
||||
return bytes;
|
||||
}
|
||||
public Evidence.ImportedReference importReference(Path root,Path source,String humanGrant) {
|
||||
try {
|
||||
Path canonical=source.toRealPath();
|
||||
boolean authorized=new Grant(root.toRealPath(),canonical).equals(grants.get(humanGrant==null?"":humanGrant));
|
||||
if(!canonical.startsWith(root.toRealPath())&&!authorized)throw denied("Reference requires project scope or explicit human selection");
|
||||
return new Evidence.ImportedReference(boundedFile(canonical,32*1024*1024),canonical.toString(),authorized);
|
||||
}catch(IOException e){throw storage("Reference unavailable",e);}
|
||||
}
|
||||
public String authorizeReference(Path root,Path source) {
|
||||
try {String grant=UUID.randomUUID().toString();grants.put(grant,new Grant(root.toRealPath(),source.toRealPath()));return grant;}
|
||||
catch(IOException e){throw storage("Reference unavailable",e);}
|
||||
}
|
||||
public void delete(Path root,String publicationId) {
|
||||
locked(root,dir->{
|
||||
id(publicationId);var all=scan(root,dir);var target=all.stream().filter(p->p.id().equals(publicationId)).findFirst().orElseThrow(FileEvidenceStore::missing);
|
||||
var ids=new HashSet<String>();target.artifacts().forEach(a->ids.add(a.id()));
|
||||
for(var p:all)if(!p.id().equals(publicationId)) {
|
||||
boolean referenced=p.report()!=null&&(ids.contains(p.report().expectedId())||ids.contains(p.report().actualId())||ids.contains(p.report().diffId()));
|
||||
referenced|=p.baseline()!=null&&(ids.contains(p.baseline().artifactId())||target.baseline()!=null&&Objects.equals(p.baseline().previousRevision(),target.baseline().id()));
|
||||
if(referenced)throw new AutomationException(AutomationFailure.Code.BUSY,"Evidence is referenced by a report or baseline");
|
||||
}
|
||||
Path targetDir=dir.resolve("pub-"+publicationId);Path trash=dir.resolve("staging-delete-"+UUID.randomUUID());
|
||||
Files.move(targetDir,trash,StandardCopyOption.ATOMIC_MOVE);removeStage(trash);return null;
|
||||
});
|
||||
}
|
||||
private static byte[] boundedFile(Path path,int max)throws IOException {
|
||||
if(Files.isSymbolicLink(path)||!Files.isRegularFile(path)||Files.size(path)>max)throw denied("Invalid or oversized evidence file");
|
||||
try(var in=Files.newInputStream(path)) {byte[] bytes=in.readNBytes(max+1);if(bytes.length>max)throw denied("Evidence file exceeds bound");return bytes;}
|
||||
}
|
||||
private static void writeDurable(Path path,byte[] bytes)throws IOException {
|
||||
try(var ch=FileChannel.open(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)) {
|
||||
var buffer=java.nio.ByteBuffer.wrap(bytes);while(buffer.hasRemaining())ch.write(buffer);ch.force(true);
|
||||
}
|
||||
}
|
||||
private static void removeStage(Path stage)throws IOException {
|
||||
try(var entries=Files.list(stage)){for(var p:entries.toList())Files.delete(p);}Files.delete(stage);
|
||||
}
|
||||
private static String id(String value) {
|
||||
if(value==null||!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))throw new IllegalArgumentException("Invalid opaque evidence ID");return value;
|
||||
}
|
||||
private static AutomationException missing(){return new AutomationException(AutomationFailure.Code.REFERENCE_NOT_FOUND,"Evidence not found in this project");}
|
||||
private static AutomationException denied(String message){return new AutomationException(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE,message);}
|
||||
private static AutomationException storage(String message,Throwable cause){return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,message);}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package p.studio.app.evidence;
|
||||
|
||||
import p.studio.api.automation.*;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
|
||||
/** PNG sample expansion only: no resize, gamma, perceptual or color-profile transform. */
|
||||
public final class PngEvidenceCodec implements EvidenceStore.Codec {
|
||||
public Evidence.Pixels decode(byte[] png) {
|
||||
try {
|
||||
if (png.length < 33 || png.length > 32*1024*1024 || png[0]!=(byte)137 || png[1]!=80 || png[2]!=78 || png[3]!=71)
|
||||
throw new IllegalArgumentException("Expected bounded PNG bytes");
|
||||
int depth=Byte.toUnsignedInt(png[24]),type=Byte.toUnsignedInt(png[25]);
|
||||
if (depth!=8 && !(type==3 && (depth==1||depth==2||depth==4)))
|
||||
throw new IllegalArgumentException("PNG must expand losslessly to RGBA8");
|
||||
try (var in=ImageIO.createImageInputStream(new ByteArrayInputStream(png))) {
|
||||
var readers=ImageIO.getImageReaders(in);
|
||||
if (!readers.hasNext()) throw new IllegalArgumentException("Unsupported PNG");
|
||||
var reader=readers.next();
|
||||
try {
|
||||
reader.setInput(in,true,true);
|
||||
int w=reader.getWidth(0),h=reader.getHeight(0);
|
||||
if (w<=0||h<=0||(long)w*h>16_777_216) throw new IllegalArgumentException("Image exceeds pixel bound");
|
||||
var image=reader.read(0);var raster=image.getRaster();var model=image.getColorModel();
|
||||
var rgba=new byte[Math.multiplyExact(Math.multiplyExact(w,h),4)];
|
||||
for(int y=0;y<h;y++)for(int x=0;x<w;x++) {
|
||||
int at=(y*w+x)*4;
|
||||
if(type==3) {
|
||||
int argb=model.getRGB(raster.getDataElements(x,y,null));
|
||||
rgba[at]=(byte)(argb>>>16);rgba[at+1]=(byte)(argb>>>8);rgba[at+2]=(byte)argb;rgba[at+3]=(byte)(argb>>>24);
|
||||
} else {
|
||||
boolean gray=type==0||type==4;
|
||||
rgba[at]=(byte)raster.getSample(x,y,0);
|
||||
rgba[at+1]=(byte)raster.getSample(x,y,gray?0:1);
|
||||
rgba[at+2]=(byte)raster.getSample(x,y,gray?0:2);
|
||||
rgba[at+3]=(byte)(model.hasAlpha()?raster.getSample(x,y,raster.getNumBands()-1):255);
|
||||
}
|
||||
}
|
||||
return new Evidence.Pixels(w,h,rgba);
|
||||
} finally {reader.dispose();}
|
||||
}
|
||||
} catch (IOException e) {throw new IllegalArgumentException("PNG decode failed",e);}
|
||||
}
|
||||
public byte[] encode(Evidence.Pixels pixels) {
|
||||
try {
|
||||
var image=new BufferedImage(pixels.width(),pixels.height(),BufferedImage.TYPE_INT_ARGB);
|
||||
var rgba=pixels.rgba();
|
||||
for(int y=0;y<pixels.height();y++)for(int x=0;x<pixels.width();x++) {
|
||||
int at=(y*pixels.width()+x)*4;
|
||||
int argb=Byte.toUnsignedInt(rgba[at+3])<<24|Byte.toUnsignedInt(rgba[at])<<16|Byte.toUnsignedInt(rgba[at+1])<<8|Byte.toUnsignedInt(rgba[at+2]);
|
||||
image.setRGB(x,y,argb);
|
||||
}
|
||||
var out=new ByteArrayOutputStream();ImageIO.write(image,"png",out);return out.toByteArray();
|
||||
} catch(IOException e) {throw new IllegalStateException("PNG encode failed",e);}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,10 @@ final class ContractSchema {
|
||||
}
|
||||
if (schema.has("not") && matches(schema.get("not"), value)) fail();
|
||||
if (schema.has("const") && !schema.get("const").equals(value)) fail();
|
||||
if (schema.has("enum")) {
|
||||
boolean found=false;for(var option:schema.get("enum"))if(option.equals(value))found=true;
|
||||
if(!found)fail();
|
||||
}
|
||||
if (schema.has("type")) {
|
||||
boolean valid = switch (schema.get("type").asText()) {
|
||||
case "null" -> value.isNull();
|
||||
@@ -23,6 +27,7 @@ final class ContractSchema {
|
||||
case "array" -> value.isArray();
|
||||
case "string" -> value.isTextual();
|
||||
case "integer" -> value.isIntegralNumber() && value.canConvertToLong();
|
||||
case "number" -> value.isNumber() && Double.isFinite(value.doubleValue());
|
||||
case "boolean" -> value.isBoolean();
|
||||
default -> throw new IllegalStateException("Unsupported packaged schema type");
|
||||
};
|
||||
@@ -30,9 +35,11 @@ final class ContractSchema {
|
||||
}
|
||||
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("maxItems")&&value.size()>schema.get("maxItems").intValue())fail();
|
||||
if(schema.path("uniqueItems").asBoolean(false)) {var items=new HashSet<JsonNode>();for(var item:value)if(!items.add(item))fail();}
|
||||
if (schema.has("minLength") && value.textValue().codePointCount(0, value.textValue().length()) < schema.get("minLength").intValue()) fail();
|
||||
if (schema.has("minimum") && value.longValue() < schema.get("minimum").longValue()) fail();
|
||||
if (schema.has("maximum") && value.longValue() > schema.get("maximum").longValue()) fail();
|
||||
if (schema.has("minimum") && value.decimalValue().compareTo(schema.get("minimum").decimalValue()) < 0) fail();
|
||||
if (schema.has("maximum") && value.decimalValue().compareTo(schema.get("maximum").decimalValue()) > 0) fail();
|
||||
if (schema.has("required")) for (var key : schema.get("required")) if (!value.has(key.asText())) fail();
|
||||
if (schema.has("properties")) {
|
||||
var allowed = new HashSet<String>();
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.app.assets.AssetBatchJson;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Thin current-task transport; no file mutation, packer validation or budget counting here. */
|
||||
public final class McpAssetAuthoringTools {
|
||||
private McpAssetAuthoringTools(){}
|
||||
public static Map<String,Function<JsonNode,McpToolResult>> handlers(AssetAuthoringService service,ObjectMapper original) {
|
||||
ObjectMapper json=AssetBatchJson.mapper(original);var handlers=new LinkedHashMap<String,Function<JsonNode,McpToolResult>>();
|
||||
handlers.put("studio_assets_catalog",a->{
|
||||
var assets=service.catalog(root(a),task(a));int offset=a.path("offset").asInt(0),limit=a.path("limit").asInt(128);
|
||||
if(offset<0||offset>assets.size()||limit<1||limit>1024)throw new IllegalArgumentException("Invalid bounded catalog page");
|
||||
int end=Math.min(assets.size(),offset+limit);return ok(json,Map.of("assets",assets.subList(offset,end),"offset",offset,"total",assets.size(),"hasMore",end<assets.size()));
|
||||
});
|
||||
handlers.put("studio_assets_revision",a->ok(json,Map.of("revision",service.revision(root(a),task(a)))));
|
||||
handlers.put("studio_assets_artifacts",a->ok(json,Map.of("artifacts",a.hasNonNull("batchId")?service.previewArtifacts(root(a),task(a),a.path("batchId").asText(),AssetReference.of(a.path("assetReference").asText())):service.artifacts(root(a),task(a),AssetReference.of(a.path("assetReference").asText())))));
|
||||
handlers.put("studio_assets_inspect",a->ok(json,Map.of("details",service.inspect(root(a),task(a),AssetReference.of(a.path("assetReference").asText())))));
|
||||
handlers.put("studio_assets_dependencies",a->ok(json,Map.of("ownership",service.dependencies(root(a),task(a),AssetReference.of(a.path("assetReference").asText())))));
|
||||
handlers.put("studio_assets_budget",a->ok(json,service.budget(root(a),task(a))));
|
||||
handlers.put("studio_assets_preview",a->ok(json,service.preview(root(a),task(a),a.path("clientRequestId").asText(),decode(json,a.path("request"),AssetBatches.Request.class))));
|
||||
handlers.put("studio_assets_preview_get",a->ok(json,service.preview(root(a),task(a),a.path("batchId").asText())));
|
||||
handlers.put("studio_assets_commit",a->ok(json,service.commit(root(a),task(a),a.path("clientRequestId").asText(),a.path("batchId").asText(),decode(json,a.path("expectedRevision"),AssetBatches.Revision.class))));
|
||||
handlers.put("studio_assets_result",a->ok(json,service.result(root(a),task(a),a.path("batchId").asText())));
|
||||
return handlers;
|
||||
}
|
||||
private static <T>T decode(ObjectMapper mapper,JsonNode value,Class<T> type){try{return mapper.treeToValue(value,type);}catch(com.fasterxml.jackson.core.JsonProcessingException invalid){throw new IllegalArgumentException("Invalid asset request",invalid);}}
|
||||
private static McpToolResult ok(ObjectMapper mapper,Object value){return McpToolResult.success(mapper,(ObjectNode)mapper.valueToTree(value));}
|
||||
private static Path root(JsonNode a){return Path.of(a.path("projectRoot").asText());}
|
||||
private static String task(JsonNode a){String task=a.path("taskId").asText();if(task.isBlank())throw new IllegalArgumentException("Current taskId required");return task;}
|
||||
}
|
||||
@@ -22,6 +22,48 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
Supply a unique clientRequestId per intended build/advance. Recover lost responses by lookup using
|
||||
clientRequestId; do not blindly repeat frame advancement with a new ID. Cancellation acknowledgement
|
||||
is not worker termination. Use only tools/capabilities actually advertised by this running Studio.
|
||||
For headless recovery, inspect observation and currentObservation separately: the former preserves
|
||||
the original operation conclusion; later session queries cannot change its frame or native cause.
|
||||
Read nativeDetails and unavailable inspections, not diagnostic prose. Unknown completedFrames is null;
|
||||
zero completed frames does not prove an unsuccessful advance had no internal effects. Recovery actions
|
||||
describe preconditions and never execute automatically. Reset is not reboot: studio_headless_reset,
|
||||
then studio_headless_boot with the same buildId, then a new intentional studio_headless_advance.
|
||||
A memcard cartridge requires an explicit memcardChoice. Use memory_fresh for a disposable RAM-only run,
|
||||
or an explicitly selected disposable test image with memcard action create/open; never silently use,
|
||||
replace or discard the user's card. Native dirty/read-only/pending-write refusals are not success.
|
||||
For declared guest test targets, use studio_tests_targets and studio_tests_start with explicit target,
|
||||
frame/block/time limits, media and discardUnsaved policy. Poll studio_tests_get by the original
|
||||
operationId/clientRequestId; studio_tests_transcript reads bounded retained events without execution.
|
||||
Cancellation uses studio_tests_cancel and is final only after workerTerminated. Historical overflow
|
||||
alone is not unread loss; preserve gap, native and producer continuity. A native failed advance,
|
||||
including one with zero completed frames, is never automatically replayed. Inspect its original cause.
|
||||
Use disposable_create then disposable_reopen with the first runId to prove save readback in a new
|
||||
process. Commit acknowledgement alone is not readback. Recover a retained cleanup refusal with an
|
||||
explicit studio_tests_shutdown policy; do not infer consent to discard pending/unsaved data.
|
||||
Release errors retain final authority and cleanup in details.control: taskRevoked means the old task
|
||||
cannot be reused even when cleanup failed. The authenticated studio_project_context exposes current
|
||||
control/runtime observations when the connection is available; otherwise inspect DEV and obtain a
|
||||
fresh human grant. Never treat the need to inspect cleanup as permission to reuse a revoked identity.
|
||||
For asset authoring, inspect studio_assets_catalog, studio_assets_artifacts, studio_assets_inspect,
|
||||
studio_assets_dependencies and studio_assets_budget. Freeze studio_assets_revision before
|
||||
studio_assets_preview. Review changed files/hashes, producer diagnostics and affected references;
|
||||
supply every explicit rebind before studio_assets_commit with the reviewed expectedRevision.
|
||||
Resolve a lost commit response through studio_assets_result; never infer rollback from cancellation.
|
||||
PNG inputs inside the project require their SHA-256; external PNGs need prior human source selection.
|
||||
Scene tiles use stable artifact identities. Generated ownership is descriptive and never runs a generator.
|
||||
Budgets separate content, existing/build banks, final preloads and potential dynamic loads.
|
||||
Sound is deferred. Unknown capacity is explicit; managed start requires the exact qualified profile.
|
||||
For visual checkpoints, studio_evidence_persist takes the ORIGINAL terminated operationId or
|
||||
sourceClientRequestId plus a publication clientRequestId. It never advances or recaptures.
|
||||
Import a project PNG with studio_evidence_import; an external path requires prior explicit human
|
||||
selection/authorization. Import does not approve a baseline. Call studio_evidence_compare with
|
||||
expectedId, actualId and parameters including explicit alpha compare/ignore; omitted tolerances
|
||||
are exact. Read the verdict, metrics, normalized ROI/masks, hashes and expected/actual/diff IDs.
|
||||
Use studio_evidence_image for direct PNG content and studio_evidence_read for bounded bytes.
|
||||
Recover a lost publication response via studio_evidence_list requestId or identical request parameters;
|
||||
never replay guest work. Evidence survives release/rebuild/reopen, but a fresh task grant is required.
|
||||
Quota refusal includes used/required/limit; deletion is explicit and reference-aware. Baseline approval
|
||||
is a human manual-control action in the DEV inspector; never promote a failed comparison automatically.
|
||||
Observe headless images/state when those tools are available, and explicitly studio_control_release
|
||||
when finished. On revocation stop external edits too: Studio cannot stop your native file writes.
|
||||
Existing edits are preserved. Git/review/recovery remain the developer's responsibility.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.api.automation.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Existing authenticated MCP transport; all evidence authority remains in shared Core. */
|
||||
public final class McpEvidenceTools {
|
||||
private McpEvidenceTools(){}
|
||||
public static Map<String,Function<JsonNode,McpToolResult>> handlers(EvidenceTools tools,ObjectMapper mapper) {
|
||||
var result=new LinkedHashMap<String,Function<JsonNode,McpToolResult>>();
|
||||
result.put("studio_evidence_persist",a->ok(mapper,tools.persist(root(a),task(a),request(a),new OperationLookup(a.path("operationId").asText(null),a.path("sourceClientRequestId").asText(null)))));
|
||||
result.put("studio_evidence_import",a->ok(mapper,tools.importReference(root(a),task(a),request(a),Path.of(a.path("path").asText()),a.path("humanGrant").asText(null))));
|
||||
result.put("studio_evidence_compare",a->ok(mapper,tools.compare(root(a),task(a),request(a),a.path("expectedId").asText(),a.path("actualId").asText(),mapper.convertValue(a.path("parameters"),Evidence.Parameters.class))));
|
||||
result.put("studio_evidence_list",a->{
|
||||
var all=tools.list(root(a),task(a));int offset=a.path("offset").asInt(0),limit=a.path("limit").asInt(50);
|
||||
if(offset>all.size())throw new IllegalArgumentException("Offset exceeds evidence history");
|
||||
int end=(int)Math.min((long)offset+limit,all.size());
|
||||
return ok(mapper,Map.of("publications",all.subList(offset,end),"offset",offset,"nextOffset",end,"total",all.size()));
|
||||
});
|
||||
result.put("studio_evidence_metadata",a->ok(mapper,tools.metadata(root(a),task(a),a.path("artifactId").asText())));
|
||||
result.put("studio_evidence_read",a->{
|
||||
var read=tools.read(root(a),task(a),a.path("artifactId").asText(),a.path("offset").longValue(),a.path("length").intValue());
|
||||
return ok(mapper,Map.of("artifactId",read.artifactId(),"offset",read.offset(),"totalBytes",read.totalBytes(),"base64",Base64.getEncoder().encodeToString(read.bytes())));
|
||||
});
|
||||
result.put("studio_evidence_image",a->{
|
||||
String id=a.path("artifactId").asText();var metadata=tools.metadata(root(a),task(a),id);
|
||||
return McpToolResult.image(mapper,mapper.valueToTree(metadata),tools.image(root(a),task(a),id));
|
||||
});
|
||||
result.put("studio_evidence_delete",a->{tools.delete(root(a),task(a),a.path("publicationId").asText());return ok(mapper,Map.of("deleted",true));});
|
||||
return result;
|
||||
}
|
||||
private static McpToolResult ok(ObjectMapper mapper,Object value){return McpToolResult.success(mapper,(ObjectNode)mapper.valueToTree(value));}
|
||||
private static Path root(JsonNode a){return Path.of(a.path("projectRoot").asText());}
|
||||
private static String task(JsonNode a){return a.path("taskId").asText();}
|
||||
private static String request(JsonNode a){return a.path("clientRequestId").asText();}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.api.automation.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Transport projection over the same guarded service used by the project Tests workspace. */
|
||||
public final class McpGuestTestTools {
|
||||
private McpGuestTestTools() { }
|
||||
public static Map<String,Function<JsonNode,McpToolResult>> handlers(GuestTestTools tools,ObjectMapper mapper) {
|
||||
var handlers=new LinkedHashMap<String,Function<JsonNode,McpToolResult>>();
|
||||
handlers.put("studio_tests_targets",a->ok(mapper,Map.of("catalog",tools.targets(root(a),task(a)))));
|
||||
handlers.put("studio_tests_start",a->{
|
||||
final GuestTestTools.Request request;
|
||||
try{request=mapper.treeToValue(a.path("request"),GuestTestTools.Request.class);}
|
||||
catch(com.fasterxml.jackson.core.JsonProcessingException bad){throw new IllegalArgumentException("Invalid test request",bad);}
|
||||
return view(mapper,tools.start(root(a),task(a),a.path("clientRequestId").asText(),request));
|
||||
});
|
||||
handlers.put("studio_tests_get",a->view(mapper,tools.get(root(a),task(a),lookup(a))));
|
||||
handlers.put("studio_tests_cancel",a->ok(mapper,Map.of("cancellationRequested",tools.cancel(root(a),task(a),a.path("operationId").asText()))));
|
||||
handlers.put("studio_tests_transcript",a->ok(mapper,tools.transcript(root(a),task(a),lookup(a),a.path("offset").asInt(0),a.path("limit").asInt(128))));
|
||||
handlers.put("studio_tests_shutdown",a->{tools.shutdown(root(a),task(a),a.path("operationId").asText(),a.path("discardUnsaved").booleanValue());return ok(mapper,Map.of("runtimeClosed",true));});
|
||||
return handlers;
|
||||
}
|
||||
public static McpToolResult view(ObjectMapper mapper,GuestTestTools.View value) {
|
||||
var result=mapper.createObjectNode().put("operationId",value.operation().id().value()).put("clientRequestId",value.clientRequestId())
|
||||
.put("runId",value.runId()).put("state",value.operation().state().name()).put("workerTerminated",value.workerTerminated()).put("runtimeRetained",value.runtimeRetained());
|
||||
result.set("progress",mapper.valueToTree(value.progress()));
|
||||
if(value.result()==null)result.putNull("result");
|
||||
else {
|
||||
ObjectNode summary=mapper.valueToTree(value.result());summary.remove("transcript");result.set("result",summary);
|
||||
}
|
||||
result.put("transcriptTotal",value.result()==null?0:value.result().transcript().size());
|
||||
result.put("transcriptTool","studio_tests_transcript");
|
||||
result.set("currentObservation",mapper.valueToTree(value.currentObservation()));
|
||||
return McpToolResult.success(mapper,result);
|
||||
}
|
||||
private static McpToolResult ok(ObjectMapper mapper,Object value){return McpToolResult.success(mapper,(ObjectNode)mapper.valueToTree(value));}
|
||||
private static Path root(JsonNode value){return Path.of(value.path("projectRoot").asText());}
|
||||
private static String task(JsonNode value){return value.path("taskId").asText();}
|
||||
private static OperationLookup lookup(JsonNode value){return new OperationLookup(value.path("operationId").asText(null),value.path("clientRequestId").asText(null));}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public final class McpTaskTools {
|
||||
var handlers = new LinkedHashMap<String, Function<JsonNode, McpToolResult>>();
|
||||
handlers.put("studio_control_acquire", args -> control(mapper, tools.acquire(root(args))));
|
||||
handlers.put("studio_control_release", args -> control(mapper, tools.release(root(args), task(args)).toCompletableFuture().join()));
|
||||
handlers.put("studio_build_start", args -> receipt(mapper, tools.build(root(args), task(args), args.path("clientRequestId").asText())));
|
||||
handlers.put("studio_build_start", args -> receipt(mapper, tools.build(root(args), task(args), args.path("clientRequestId").asText(), args.path("targetId").asText(GuestTests.PRODUCTION))));
|
||||
handlers.put("studio_operation_get", args -> operation(mapper, tools.operation(root(args), task(args),
|
||||
new OperationLookup(args.path("operationId").asText(null), args.path("clientRequestId").asText(null)))));
|
||||
handlers.put("studio_operation_cancel", args -> McpToolResult.success(mapper, mapper.createObjectNode()
|
||||
@@ -36,7 +36,7 @@ public final class McpTaskTools {
|
||||
default -> Map.of();
|
||||
};
|
||||
var result = tools.headless(root(args), task(args), action, args.path("buildId").asText(null), input);
|
||||
return result.capture() != null ? McpToolResult.capture(mapper, result.capture(), false)
|
||||
return result.capture() != null ? McpToolResult.capture(mapper, result.capture(), false, result.values())
|
||||
: McpToolResult.success(mapper, mapper.valueToTree(result.values()));
|
||||
});
|
||||
}
|
||||
@@ -65,9 +65,14 @@ public final class McpTaskTools {
|
||||
case NOT_GRANTED -> AutomationFailure.Code.NOT_GRANTED;
|
||||
default -> AutomationFailure.Code.BUSY;
|
||||
};
|
||||
return McpToolResult.failure(mapper, new AutomationFailure(code, result.diagnostic()));
|
||||
var observation = result.observation();
|
||||
return McpToolResult.failure(mapper, new AutomationFailure(code, result.diagnostic(),
|
||||
observation != null && observation.failure() != null ? observation.failure().runtimeError() : Map.of(),
|
||||
observation == null ? Map.of() : Map.of("control", mapper.convertValue(observation, Map.class))));
|
||||
}
|
||||
var value = mapper.createObjectNode().put("state", result.task() == null ? "MANUAL" : "AGENT_WORKING");
|
||||
var value = mapper.createObjectNode().put("state", result.observation() == null
|
||||
? result.task() == null ? "MANUAL" : "AGENT_WORKING" : result.observation().state().name());
|
||||
value.set("control", mapper.valueToTree(result.observation()));
|
||||
if (result.task() != null) value.put("taskId", result.task().value());
|
||||
return McpToolResult.success(mapper, value);
|
||||
}
|
||||
@@ -81,6 +86,8 @@ public final class McpTaskTools {
|
||||
value.put("workerTerminated", operation.workerTerminated());
|
||||
value.set("progress", mapper.valueToTree(operation.progress()));
|
||||
value.set("failure", mapper.valueToTree(operation.failure()));
|
||||
value.set("observation", mapper.valueToTree(operation.observation()));
|
||||
value.set("currentObservation", mapper.valueToTree(operation.currentObservation()));
|
||||
value.putNull("result");
|
||||
if (operation.buildResult() != null) {
|
||||
var build = operation.buildResult();
|
||||
@@ -100,6 +107,7 @@ public final class McpTaskTools {
|
||||
var result = value.putObject("result").put("kind", "runtime").put("status", runtime.kind().name())
|
||||
.put("requestedFrames", runtime.requestedFrames()).put("completedFrames", runtime.completedFrames());
|
||||
result.set("diagnostics", mapper.valueToTree(runtime.diagnostics()));
|
||||
result.set("observation", mapper.valueToTree(runtime.observation()));
|
||||
capture = runtime.capture();
|
||||
}
|
||||
return McpToolResult.successWithCapture(mapper, value, capture, operation.captureStale());
|
||||
|
||||
@@ -22,11 +22,15 @@ public final class McpToolResult {
|
||||
return envelope(mapper, data, true);
|
||||
}
|
||||
public static McpToolResult capture(ObjectMapper mapper, CanonicalCapture capture, boolean stale) {
|
||||
return capture(mapper, capture, stale, java.util.Map.of());
|
||||
}
|
||||
public static McpToolResult capture(ObjectMapper mapper, CanonicalCapture capture, boolean stale, java.util.Map<String, Object> facts) {
|
||||
Objects.requireNonNull(capture);
|
||||
var metadata = mapper.createObjectNode().put("sessionId", capture.sessionId()).put("buildId", capture.buildId())
|
||||
.put("logicalFrameIndex", capture.logicalFrameIndex()).put("frameId", capture.frameId())
|
||||
.put("width", capture.width()).put("height", capture.height()).put("stridePixels", capture.stridePixels())
|
||||
.put("pixelFormat", "RGBA8888").put("mimeType", "image/png").put("stale", stale);
|
||||
facts.forEach((key, item) -> metadata.set(key, mapper.valueToTree(item)));
|
||||
var result = success(mapper, metadata);
|
||||
result.wire.withArray("content").addObject().put("type", "image").put("mimeType", "image/png")
|
||||
.put("data", Base64.getEncoder().encodeToString(capture.png()));
|
||||
@@ -40,6 +44,12 @@ public final class McpToolResult {
|
||||
result.wire.withArray("content").add(image.wire.withArray("content").get(1).deepCopy());
|
||||
return result;
|
||||
}
|
||||
public static McpToolResult image(ObjectMapper mapper, ObjectNode metadata, byte[] png) {
|
||||
var result = success(mapper, metadata);
|
||||
result.wire.withArray("content").addObject().put("type", "image").put("mimeType", "image/png")
|
||||
.put("data", Base64.getEncoder().encodeToString(png));
|
||||
return result;
|
||||
}
|
||||
private static McpToolResult envelope(ObjectMapper mapper, JsonNode data, boolean error) {
|
||||
var wire = mapper.createObjectNode().put("isError", error);
|
||||
wire.set("structuredContent", data);
|
||||
|
||||
@@ -34,6 +34,7 @@ public final class ExternalRuntimeGateway implements RuntimeGateway {
|
||||
Consumer<RuntimeLogEntry> logs) throws Exception {
|
||||
final Consumer<RuntimeLogEntry> sink = Objects.requireNonNull(logs, "logs");
|
||||
final Path executable = resolveExecutable(setup);
|
||||
new p.studio.app.assets.ManagedAssetGuard(mapper).require(project.rootPath(),project.rootPath().resolve("build"),setup);
|
||||
final Process process = new ProcessBuilder(command(executable, project, setup))
|
||||
.directory(project.rootPath().toFile()).start();
|
||||
stream(process.getInputStream(), false, sink);
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.GuestTests;
|
||||
import java.util.*;
|
||||
|
||||
/** Versioned tagged-event codec; ordinary native game records never reach this decoder. */
|
||||
public final class GuestEventDecoder implements GuestTests.Decoder {
|
||||
private final ObjectMapper mapper;
|
||||
public GuestEventDecoder(ObjectMapper mapper){this.mapper=Objects.requireNonNull(mapper);}
|
||||
public GuestTests.Event decode(String message) {
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode value=mapper.reader()
|
||||
.with(com.fasterxml.jackson.core.JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
|
||||
.with(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(message);
|
||||
if(value==null||!value.isObject())throw new IllegalArgumentException("Expected event object");
|
||||
value.fieldNames().forEachRemaining(name->{if(!Set.of("schemaVersion","suiteId","caseId","eventId","kind","payload").contains(name))throw new IllegalArgumentException("Unknown event field");});
|
||||
if(!value.path("schemaVersion").isIntegralNumber()||!value.path("schemaVersion").canConvertToInt()
|
||||
||!value.path("suiteId").isTextual()||!value.path("eventId").isTextual()||!value.path("kind").isTextual()
|
||||
||!value.path("payload").isObject()||value.has("caseId")&&!value.path("caseId").isNull()&&!value.path("caseId").isTextual())
|
||||
throw new IllegalArgumentException("Invalid typed event envelope");
|
||||
return mapper.treeToValue(value,GuestTests.Event.class);
|
||||
}catch(java.io.IOException invalid){throw new IllegalArgumentException("Invalid tagged JSON event",invalid);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import p.studio.compiler.messages.BuildingIssueSink;
|
||||
import p.studio.compiler.utilities.PrometeuManifestUtils;
|
||||
import p.studio.core.runtime.GuestTestSupport;
|
||||
import java.nio.file.*;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/** Application persistence only: common manifest resolution, owned run media and shared evidence. */
|
||||
public final class GuestTestSupportAdapter implements GuestTestSupport {
|
||||
private final ObjectMapper mapper;
|
||||
private final EvidenceStore evidence;
|
||||
private final EvidenceStore.Codec pixels;
|
||||
public GuestTestSupportAdapter(ObjectMapper mapper,EvidenceStore evidence,EvidenceStore.Codec pixels){this.mapper=mapper;this.evidence=evidence;this.pixels=pixels;}
|
||||
@Override public GuestTests.Catalog targets(ProjectReference project) {
|
||||
return catalog(manifest(project));
|
||||
}
|
||||
private p.studio.compiler.models.PrometeuManifest manifest(ProjectReference project) {
|
||||
try {
|
||||
var root=project.rootPath().toRealPath();var issues=BuildingIssueSink.empty();
|
||||
return PrometeuManifestUtils.buildManifest(root,root.resolve("prometeu.json").toRealPath(),issues)
|
||||
.orElseThrow(()->new IllegalArgumentException("Invalid project manifest/testTargets: "+issues));
|
||||
}catch(java.io.IOException failure){throw new IllegalArgumentException("Cannot read project test targets",failure);}
|
||||
}
|
||||
private static GuestTests.Catalog catalog(p.studio.compiler.models.PrometeuManifest manifest) {
|
||||
return new GuestTests.Catalog(manifest.testTargets().schemaVersion(),manifest.testTargets().targets().stream()
|
||||
.map(t->new GuestTests.Target(t.id(),t.entrypoint(),t.sourceRoots(),t.supportRoots(),t.exclusions(),t.cases(),t.logTag())).toList());
|
||||
}
|
||||
@Override public GuestTests.Target targetAtBuild(ProjectReference project,p.studio.api.shipper.ShipperPrepareResult build,String targetId)throws Exception {
|
||||
var manifest=manifest(project);
|
||||
Object hashes=build.context().get("configurationSha256");
|
||||
Object expected=hashes instanceof Map<?,?> map?map.get(project.rootPath().toRealPath().resolve("prometeu.json").toString()):null;
|
||||
if(!manifest.manifestSha256().equals(expected))throw new IllegalArgumentException("Project test catalog changed since the immutable build");
|
||||
return catalog(manifest).targets().stream().filter(target->target.id().equals(targetId)).findFirst().orElseThrow(()->new IllegalArgumentException("Built target catalog is unavailable"));
|
||||
}
|
||||
@Override public Map<String,Object> media(ProjectReference project,String runId,GuestTestTools.Request request)throws Exception {
|
||||
Path directory=directory(project.rootPath(),runId);Files.createDirectory(directory);
|
||||
var descriptor=new LinkedHashMap<String,Object>();descriptor.put("runId",runId);descriptor.put("media",request.media().name());
|
||||
descriptor.put("reopenRunId",request.reopenRunId());
|
||||
Map<String,Object> options;
|
||||
if(request.media()==GuestTestTools.Media.memory_fresh) {
|
||||
// A cartridge without memcard_slots has no card namespace or boot choice.
|
||||
// A new process already guarantees fresh RAM; never invent a card declaration.
|
||||
descriptor.put("memcardApplicable",project.memcardSlots()!=null);
|
||||
options=project.memcardSlots()==null?Map.of():Map.of("memcardChoice","memory_fresh");
|
||||
}
|
||||
else {
|
||||
if(project.memcardSlots()==null)throw new IllegalArgumentException("Disposable card requires declared memcard_slots");
|
||||
Path image;
|
||||
if(request.media()==GuestTestTools.Media.disposable_create)image=directory.resolve("memcard.pmc");
|
||||
else {
|
||||
Path owner=directory(project.rootPath(),request.reopenRunId());
|
||||
var original=mapper.readTree(owner.resolve("media.json").toFile());
|
||||
if(!original.path("runId").asText().equals(request.reopenRunId())||!original.path("media").asText().equals("disposable_create"))
|
||||
throw new IllegalArgumentException("Reopen requires a prior owned disposable-create image");
|
||||
image=owner.resolve("memcard.pmc");
|
||||
if(Files.isSymbolicLink(image)||!Files.isRegularFile(image)||!image.toRealPath().startsWith(owner.toRealPath()))
|
||||
throw new IllegalArgumentException("Owned test image unavailable or outside its run");
|
||||
}
|
||||
descriptor.put("image",image.toString());
|
||||
options=Map.of("memcardChoice","persistent","memcard",Map.of("path",image.toString(),"action",
|
||||
request.media()==GuestTestTools.Media.disposable_create?"create":"open","access","read_write"));
|
||||
}
|
||||
atomic(directory.resolve("media.json"),descriptor);return options;
|
||||
}
|
||||
@Override public long applicationId(p.studio.api.shipper.ShipperPrepareResult build)throws Exception {
|
||||
var id=mapper.readTree(build.manifestPath().toFile()).path("app_id");
|
||||
if(!id.isIntegralNumber()||!id.canConvertToLong()||id.longValue()<0||id.longValue()>0xffff_ffffL)
|
||||
throw new IllegalArgumentException("Immutable test manifest has no valid application identity");
|
||||
return id.longValue();
|
||||
}
|
||||
@Override public void completed(ProjectReference project,String runId,GuestTests.RunResult result)throws Exception {
|
||||
Path directory=directory(project.rootPath(),runId);Files.createDirectories(directory);
|
||||
atomic(directory.resolve("result.json"),result);
|
||||
}
|
||||
private Path directory(Path project,String runId)throws Exception {
|
||||
UUID.fromString(runId);Path root=project.toRealPath();Path parent=root.resolve(".studio/test-runs");
|
||||
Path ancestor=parent;while(!Files.exists(ancestor))ancestor=ancestor.getParent();
|
||||
if(!ancestor.toRealPath().startsWith(root))throw new IllegalArgumentException("Test storage escapes project scope");
|
||||
Files.createDirectories(parent);if(!parent.toRealPath().startsWith(root))throw new IllegalArgumentException("Test storage escapes project scope");
|
||||
Path directory=parent.resolve(runId);
|
||||
if(Files.exists(directory)&&(Files.isSymbolicLink(directory)||!directory.toRealPath().startsWith(parent.toRealPath())))
|
||||
throw new IllegalArgumentException("Test run directory escapes storage scope");
|
||||
return directory;
|
||||
}
|
||||
private void atomic(Path target,Object value)throws Exception {
|
||||
byte[] bytes=mapper.writeValueAsBytes(value);Path temporary=target.resolveSibling(".staging-"+UUID.randomUUID());
|
||||
try {
|
||||
try(var channel=FileChannel.open(temporary,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){
|
||||
var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);
|
||||
}
|
||||
Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);
|
||||
}finally{Files.deleteIfExists(temporary);}
|
||||
}
|
||||
@Override public boolean admitsCheckpoint(Path root,String id) {
|
||||
return evidence.list(root).stream().flatMap(p->p.artifacts().stream()).anyMatch(a->a.id().equals(id));
|
||||
}
|
||||
@Override public String retainCapture(Path root,String runId,String operationId,String requestId,CanonicalCapture capture)throws Exception {
|
||||
var decoded=pixels.decode(capture.png());
|
||||
if(decoded.width()!=capture.width()||decoded.height()!=capture.height())throw new IllegalArgumentException("Capture metadata mismatch");
|
||||
String publication=UUID.randomUUID().toString(),id=UUID.randomUUID().toString();
|
||||
var provenance=ValueMaps.fields("origin","runtime","projectRoot",root.toString(),"runId",runId,"operationId",operationId,
|
||||
"clientRequestId",requestId,"buildId",capture.buildId(),"sessionId",capture.sessionId(),"logicalFrameIndex",capture.logicalFrameIndex(),"frameId",capture.frameId());
|
||||
var artifact=new Evidence.Artifact(id,publication,HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(capture.png())),capture.png().length,
|
||||
"image/png",capture.width(),capture.height(),provenance);
|
||||
evidence.publish(root,new Evidence.Publication(publication,"guest-test-capture:"+runId,"guest-test:"+runId,root.toString(),Instant.now().toString(),List.of(artifact),null,null),List.of(new Evidence.Blob(artifact,capture.png())));
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,12 @@ public final class HeadlessProcessGateway implements HeadlessGateway {
|
||||
return boot(project, buildId, build, Map.of());
|
||||
}
|
||||
@Override public Session boot(ProjectReference project, String buildId, ShipperPrepareResult build, Map<String, Object> options) throws Exception {
|
||||
return boot(project, buildId, build, options, false);
|
||||
}
|
||||
@Override public Session bootTest(ProjectReference project, String buildId, ShipperPrepareResult build, Map<String, Object> options) throws Exception {
|
||||
return boot(project, buildId, build, options, true);
|
||||
}
|
||||
private Session boot(ProjectReference project, String buildId, ShipperPrepareResult build, Map<String, Object> options, boolean test) throws Exception {
|
||||
var localSetup = setup.apply(project);
|
||||
String installation = localSetup.prometeuRuntimePath();
|
||||
if (installation == null) throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Configure the project runtime installation first");
|
||||
@@ -34,17 +40,27 @@ public final class HeadlessProcessGateway implements HeadlessGateway {
|
||||
throw new AutomationException(AutomationFailure.Code.BUILD_NOT_FOUND, "Successful build manifest is unavailable");
|
||||
Path root = project.rootPath().toRealPath(), manifest = build.manifestPath().toRealPath();
|
||||
if (!manifest.startsWith(root)) throw new AutomationException(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Build manifest is outside the project");
|
||||
new p.studio.app.assets.ManagedAssetGuard(mapper).require(root,manifest.getParent(),localSetup);
|
||||
var command = new ArrayList<String>(); command.add(executable.toString()); command.addAll(limits.arguments());
|
||||
final Process process;
|
||||
try { process = new ProcessBuilder(command).directory(root.toFile()).start(); }
|
||||
catch (java.io.IOException unavailable) { throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Cannot launch the configured runtime"); }
|
||||
var session = new HeadlessProcessSession(process, mapper, limits, buildId);
|
||||
session.bootAdmission(() -> new p.studio.app.assets.ManagedAssetGuard(mapper)
|
||||
.require(root, manifest.getParent(), setup.apply(project)));
|
||||
try {
|
||||
session.initializeAndBoot(manifest.getParent(), root, project.memcardSlots() != null || !options.isEmpty(), options,
|
||||
localSetup.memcardPath() == null ? root.resolve(".studio/memcard.pmc")
|
||||
: p.studio.core.project.ProjectCartridgeConfiguration.selectedImage(project, localSetup));
|
||||
: p.studio.core.project.ProjectCartridgeConfiguration.selectedImage(project, localSetup), test);
|
||||
return session;
|
||||
}
|
||||
catch (Exception failure) { session.abort("Headless startup failed"); throw failure; }
|
||||
catch (Exception failure) {
|
||||
session.abort("Headless startup failed");
|
||||
if (failure instanceof AutomationException domain) {
|
||||
var original = domain.failure();
|
||||
throw new AutomationException(new AutomationFailure(original.code(), original.message(), original.runtimeError(), original.details(), session.observation()));
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
private final String buildId;
|
||||
private volatile String sessionId;
|
||||
private volatile JsonNode hello;
|
||||
private volatile RuntimeObservation observed;
|
||||
private Path cartridge;
|
||||
private Path projectRoot;
|
||||
private Path selectedImage;
|
||||
@@ -37,10 +38,15 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
private final AtomicReference<Pending> advance = new AtomicReference<>();
|
||||
private final Deque<String> stderr = new ArrayDeque<>();
|
||||
private volatile boolean closing;
|
||||
private boolean logReadEnabled;
|
||||
private CompletableFuture<TaskTools.HeadlessReply> shutdown;
|
||||
private java.util.concurrent.Callable<?> bootAdmission = () -> null;
|
||||
|
||||
void bootAdmission(java.util.concurrent.Callable<?> admission) { bootAdmission = java.util.Objects.requireNonNull(admission); }
|
||||
|
||||
HeadlessProcessSession(Process process, ObjectMapper source, HeadlessLimits limits, String buildId) {
|
||||
this.process = process; this.limits = limits; this.buildId = buildId;
|
||||
observed = RuntimeObservation.unknown(null, buildId);
|
||||
mapper = source.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
mapper.getFactory().setStreamReadConstraints(StreamReadConstraints.builder().maxStringLength(limits.maxResponseBytes()).build());
|
||||
timer.scheduleAtFixedRate(() -> { if (process.isAlive()) process.descendants().forEach(descendants::add); }, 0, 20, TimeUnit.MILLISECONDS);
|
||||
@@ -55,6 +61,9 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
initializeAndBoot(cartridge, projectRoot, memcard, options, projectRoot.resolve(".studio/memcard.pmc"));
|
||||
}
|
||||
void initializeAndBoot(Path cartridge, Path projectRoot, boolean memcard, Map<String, Object> options, Path selectedImage) throws Exception {
|
||||
initializeAndBoot(cartridge, projectRoot, memcard, options, selectedImage, false);
|
||||
}
|
||||
void initializeAndBoot(Path cartridge, Path projectRoot, boolean memcard, Map<String, Object> options, Path selectedImage, boolean logRead) throws Exception {
|
||||
this.cartridge = cartridge;
|
||||
this.projectRoot = projectRoot;
|
||||
this.selectedImage = selectedImage;
|
||||
@@ -64,6 +73,13 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
hello = await(greeting, limits.handshakeTimeoutMs());
|
||||
version(hello.path("protocolVersion")); text(hello, "runtimeVersion"); capabilities(hello.path("capabilities"));
|
||||
var required = new HashSet<>(CAPABILITIES);
|
||||
if (logRead) {
|
||||
boolean available = false;
|
||||
for (var capability : hello.path("capabilities")) if (capability.asText().equals("log_read")) available = true;
|
||||
if (count(hello.path("protocolVersion"), "minor") < 2 || !available)
|
||||
throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Structured tests require protocol 1.2/log_read before boot");
|
||||
required.add("log_read");
|
||||
}
|
||||
if (memcard) {
|
||||
if (count(hello.path("protocolVersion"), "minor") < 1) throw incompatibleMemcard();
|
||||
boolean available = false;
|
||||
@@ -77,32 +93,59 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
if (count(hello.path("limits"), field) != expected.path(field).longValue())
|
||||
throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Runtime limits do not match launch configuration");
|
||||
}
|
||||
var init = mapper.createObjectNode(); init.putObject("protocolVersion").put("major", 1).put("minor", memcard ? 1 : 0);
|
||||
var init = mapper.createObjectNode(); init.putObject("protocolVersion").put("major", 1).put("minor", logRead ? 2 : memcard ? 1 : 0);
|
||||
init.set("requiredCapabilities", mapper.valueToTree(required));
|
||||
var negotiated = request("initialize", init, null, remaining(deadline));
|
||||
version(negotiated.path("protocolVersion")); capabilities(negotiated.path("capabilities"));
|
||||
if (logRead) {
|
||||
boolean available = false;
|
||||
for (var capability : negotiated.path("capabilities")) if (capability.asText().equals("log_read")) available = true;
|
||||
if (count(negotiated.path("protocolVersion"), "minor") < 2 || !available)
|
||||
throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Runtime did not negotiate log_read");
|
||||
}
|
||||
logReadEnabled = logRead;
|
||||
if (memcard) {
|
||||
boolean available = false;
|
||||
for (var capability : negotiated.path("capabilities")) if (capability.asText().equals("memcard")) available = true;
|
||||
if (count(negotiated.path("protocolVersion"), "minor") < 1 || !available) throw incompatibleMemcard();
|
||||
}
|
||||
memcardEnabled = memcard;
|
||||
state(boot(bootOptions));
|
||||
updateObservation(value -> value.transition(RuntimeObservation.Lifecycle.UNKNOWN, "initialize", Map.of(
|
||||
"runtimeVersion", text(hello, "runtimeVersion"), "limits", mapper.convertValue(hello.path("limits"), Object.class),
|
||||
"capabilities", mapper.convertValue(hello.path("capabilities"), Object.class))));
|
||||
try { observeState(boot(bootOptions), RuntimeObservation.Lifecycle.BOOTED, "boot"); }
|
||||
catch (AutomationException failure) { rememberFailure("boot", failure.failure()); throw observedFailure(failure); }
|
||||
}
|
||||
private static AutomationException incompatibleMemcard() {
|
||||
return new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Configured runtime requires protocol 1.1 and memcard capability");
|
||||
}
|
||||
private JsonNode boot(JsonNode options) throws Exception {
|
||||
bootAdmission.call();
|
||||
var params = HeadlessMemcard.boot(mapper, cartridge, options);
|
||||
if (options.has("memcard")) {
|
||||
if (!memcardEnabled) throw incompatibleMemcard();
|
||||
HeadlessMemcard.state(request("memcard_mount", HeadlessMemcard.mount(mapper, projectRoot, options.path("memcard"), selectedImage), null, limits.callTimeoutMs()));
|
||||
observeMemcard(request("memcard_mount", HeadlessMemcard.mount(mapper, projectRoot, options.path("memcard"), selectedImage), null, limits.callTimeoutMs()), "memcard_mount");
|
||||
}
|
||||
if (options.has("memcardChoice") && !memcardEnabled) throw incompatibleMemcard();
|
||||
return request("boot", params, null, limits.callTimeoutMs());
|
||||
}
|
||||
@Override public String sessionId() { return sessionId; }
|
||||
@Override public RuntimeObservation observation() { return observed; }
|
||||
@Override public long maxFramesPerAdvance() { return limits.maxFrames(); }
|
||||
@Override public GuestTests.LogPage logs(java.math.BigInteger afterSequence, int limit) throws Exception {
|
||||
if (!logReadEnabled) throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "log_read was not negotiated");
|
||||
if (limit < 1 || limit > 1024 || afterSequence != null && (afterSequence.signum() < 0 || afterSequence.bitLength() > 64))
|
||||
throw new IllegalArgumentException("Invalid native log cursor/limit");
|
||||
if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active");
|
||||
try {
|
||||
if (closing) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless shutdown active");
|
||||
var params = mapper.createObjectNode().put("limit", limit);
|
||||
if (afterSequence == null) params.putNull("afterSequence"); else params.put("afterSequence", afterSequence);
|
||||
return HeadlessWire.logs(request("get_logs", params, null, limits.callTimeoutMs()), sessionId, afterSequence, limit);
|
||||
} catch (AutomationException failure) {
|
||||
invalidateMalformed(failure); rememberFailure("get_logs", failure.failure()); throw observedFailure(failure);
|
||||
} finally { work.unlock(); }
|
||||
}
|
||||
long pid() { return process.pid(); }
|
||||
boolean alive() { return process.isAlive() || descendants.stream().anyMatch(ProcessHandle::isAlive); }
|
||||
|
||||
@@ -132,22 +175,29 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
var values = new LinkedHashMap<String, Object>(); values.put("sessionId", sessionId); values.put("buildId", buildId);
|
||||
CanonicalCapture capture = null;
|
||||
switch (action) {
|
||||
case CAPTURE -> capture = capture(result, sessionId, buildId);
|
||||
case CAPTURE -> {
|
||||
var frame = capture(result, sessionId, buildId); capture = frame;
|
||||
updateObservation(value -> value.withCapture(frame));
|
||||
}
|
||||
case STATE, RESET, BOOT -> {
|
||||
state(result); values.put("state", mapper.convertValue(result, Object.class));
|
||||
observeState(result, action == TaskTools.HeadlessAction.RESET ? RuntimeObservation.Lifecycle.UNBOOTED
|
||||
: action == TaskTools.HeadlessAction.BOOT ? RuntimeObservation.Lifecycle.BOOTED : currentLifecycle(), command);
|
||||
values.put("state", mapper.convertValue(result, Object.class));
|
||||
values.put("runtimeVersion", text(hello, "runtimeVersion"));
|
||||
values.put("limits", mapper.convertValue(hello.path("limits"), Object.class));
|
||||
values.put("capabilities", mapper.convertValue(hello.path("capabilities"), Object.class));
|
||||
if (memcardEnabled && action == TaskTools.HeadlessAction.RESET) HeadlessMemcard.state(result.path("memcard"));
|
||||
if (memcardEnabled && action == TaskTools.HeadlessAction.RESET) observeMemcard(result.path("memcard"), command);
|
||||
}
|
||||
case FAULT -> { fault(result); values.put("fault", mapper.convertValue(result, Object.class)); }
|
||||
case FAULT -> { fault(result); values.put("fault", mapper.convertValue(result, Object.class));
|
||||
updateObservation(value -> value.transition(value.lifecycle(), command, p.studio.utilities.json.ImmutableJson.fields("fault", mapper.convertValue(result, Object.class)))); }
|
||||
case MEMCARD_STATE, MEMCARD_MOUNT, MEMCARD_UNMOUNT, MEMCARD_RECONCILE, MEMCARD_CONTINUE_IN_MEMORY -> {
|
||||
HeadlessMemcard.state(result); values.put("memcard", mapper.convertValue(result, Object.class));
|
||||
observeMemcard(result, command); values.put("memcard", mapper.convertValue(result, Object.class));
|
||||
}
|
||||
default -> { if (!result.isObject()) throw invalid("Invalid acknowledgement"); }
|
||||
}
|
||||
values.put("observation", observed);
|
||||
return new TaskTools.HeadlessReply(values, capture);
|
||||
} catch (AutomationException failure) { invalidateMalformed(failure); throw failure; }
|
||||
} catch (AutomationException failure) { invalidateMalformed(failure); rememberFailure(action.name(), failure.failure()); throw observedFailure(failure); }
|
||||
finally { work.unlock(); }
|
||||
}
|
||||
|
||||
@@ -157,6 +207,7 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
boolean interrupted = false;
|
||||
try {
|
||||
if (closing) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless shutdown active");
|
||||
updateObservation(value -> value.beginAdvance(frames));
|
||||
var item = new Pending("advance", frames, progress); advance.set(item);
|
||||
send(item, mapper.createObjectNode().put("frames", frames));
|
||||
JsonNode result;
|
||||
@@ -167,11 +218,15 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
} catch (TimeoutException timedOut) {
|
||||
cancel();
|
||||
try { awaitUninterruptibly(item.result, limits.shutdownTimeoutMs()); } catch (Exception ignored) { }
|
||||
abort("Headless advance deadline exceeded"); throw infrastructure("Headless advance deadline exceeded");
|
||||
var failure = infrastructure("Headless advance deadline exceeded", "deadline");
|
||||
abort(failure.failure()); throw failure;
|
||||
}
|
||||
long requested = count(result, "requested"), completed = count(result, "completed");
|
||||
final JsonNode nativeResult = result;
|
||||
if (requested != frames || completed > frames || completed < item.completed) throw invalid("Inconsistent final progress");
|
||||
updateObservation(value -> value.withProgress(new TrackedOperation.Progress(frames, completed)));
|
||||
progress.accept(new TrackedOperation.Progress(frames, completed));
|
||||
updateObservation(value -> value.transition(value.lifecycle(), "advance", Map.of("advance", mapper.convertValue(nativeResult, Object.class))));
|
||||
var diagnostics = new ArrayList<String>();
|
||||
var kind = switch (text(result, "stop")) {
|
||||
case "completed" -> { if (completed != frames) throw invalid("Incomplete completed result"); yield AutomationOutcome.Kind.SUCCEEDED; }
|
||||
@@ -179,23 +234,42 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
case "terminated" -> AutomationOutcome.Kind.TERMINATED;
|
||||
case "action_required" -> {
|
||||
if (!memcardEnabled) throw invalid("Unnegotiated memcard outcome");
|
||||
var nativeState = request("get_memcard_state", mapper.createObjectNode(), null, limits.callTimeoutMs());
|
||||
HeadlessMemcard.state(nativeState); diagnostics.add(nativeState.toString());
|
||||
yield AutomationOutcome.Kind.ACTION_REQUIRED;
|
||||
}
|
||||
case "faulted" -> { fault(result.path("fault")); if (result.path("fault").isNull()) throw invalid("Missing fault"); diagnostics.add(result.path("fault").toString()); yield AutomationOutcome.Kind.GUEST_FAULT; }
|
||||
case "host_error" -> { error(result.path("error")); diagnostics.add(result.path("error").toString()); yield AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE; }
|
||||
case "faulted" -> {
|
||||
fault(result.path("fault")); if (result.path("fault").isNull()) throw invalid("Missing fault");
|
||||
updateObservation(value -> value.transition(value.lifecycle(), "advance", Map.of("fault", mapper.convertValue(nativeResult.path("fault"), Object.class))));
|
||||
diagnostics.add(result.path("fault").toString()); yield AutomationOutcome.Kind.GUEST_FAULT;
|
||||
}
|
||||
case "host_error" -> {
|
||||
error(result.path("error"));
|
||||
updateObservation(value -> value.transition(value.lifecycle(), "advance", Map.of("error", mapper.convertValue(nativeResult.path("error"), Object.class))));
|
||||
diagnostics.add(result.path("error").toString()); yield AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE;
|
||||
}
|
||||
default -> throw invalid("Unknown advance stop");
|
||||
};
|
||||
CanonicalCapture captured = null;
|
||||
if (!closing) {
|
||||
try { captured = capture(request("capture", mapper.createObjectNode(), null, limits.callTimeoutMs()), sessionId, buildId); }
|
||||
catch (AutomationException noFrame) { if (noFrame.failure().code() != AutomationFailure.Code.NO_FRAME_AVAILABLE) throw noFrame; }
|
||||
try {
|
||||
var frame = capture(request("capture", mapper.createObjectNode(), null, limits.callTimeoutMs()), sessionId, buildId);
|
||||
captured = frame; updateObservation(value -> value.withCapture(frame));
|
||||
} catch (AutomationException noFrame) {
|
||||
if (noFrame.failure().code() != AutomationFailure.Code.NO_FRAME_AVAILABLE
|
||||
&& !closing
|
||||
&& kind != AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE && kind != AutomationOutcome.Kind.GUEST_FAULT
|
||||
&& kind != AutomationOutcome.Kind.ACTION_REQUIRED) throw noFrame;
|
||||
invalidateMalformed(noFrame);
|
||||
updateObservation(value -> value.unavailable("capture", noFrame.failure()));
|
||||
}
|
||||
}
|
||||
inspectAfterAdvance(kind == AutomationOutcome.Kind.ACTION_REQUIRED);
|
||||
if (kind != AutomationOutcome.Kind.SUCCEEDED && kind != AutomationOutcome.Kind.CANCELLED)
|
||||
updateObservation(RuntimeObservation::markCaptureStale);
|
||||
synchronized (stderr) { diagnostics.addAll(stderr); stderr.clear(); }
|
||||
return new AutomationOutcome(kind, requested, completed, diagnostics, captured);
|
||||
} catch (TimeoutException timeout) { abort("Cancellation deadline exceeded"); throw infrastructure("Cancellation deadline exceeded"); }
|
||||
catch (AutomationException failure) { invalidateMalformed(failure); throw failure; }
|
||||
return new AutomationOutcome(kind, requested, completed, diagnostics, captured, Map.of(), observed);
|
||||
} catch (TimeoutException timeout) {
|
||||
var failure = infrastructure("Cancellation deadline exceeded", "deadline"); abort(failure.failure()); throw failure;
|
||||
} catch (AutomationException failure) { invalidateMalformed(failure); rememberFailure("advance", failure.failure()); throw observedFailure(failure); }
|
||||
finally { advance.set(null); work.unlock(); if (interrupted) Thread.currentThread().interrupt(); }
|
||||
}
|
||||
|
||||
@@ -223,7 +297,7 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
// The first forced shutdown reports infrastructure failure. An explicit human
|
||||
// retry may acknowledge completed cleanup, but never releases a living process.
|
||||
if (!shutdown.isCompletedExceptionally()) return shutdown;
|
||||
if (dead.get() && !alive()) return CompletableFuture.completedFuture(new TaskTools.HeadlessReply(Map.of("sessionId", sessionId), null));
|
||||
if (dead.get() && !alive()) return CompletableFuture.completedFuture(terminatedReply("cleanup_confirmed"));
|
||||
// A native refusal leaves this channel usable for an explicit retry.
|
||||
if (closing) return shutdown;
|
||||
}
|
||||
@@ -234,24 +308,29 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
if (!dead.get()) {
|
||||
var response = request("shutdown", params, null, remaining(deadline));
|
||||
if (!response.path("closed").isBoolean() || !response.path("closed").booleanValue()) throw invalid("Missing shutdown acknowledgement");
|
||||
if (memcardEnabled) HeadlessMemcard.state(response.path("memcard"));
|
||||
if (memcardEnabled) observeMemcard(response.path("memcard"), "shutdown");
|
||||
if (!process.waitFor(remaining(deadline), TimeUnit.MILLISECONDS)) throw new TimeoutException();
|
||||
terminate();
|
||||
if (alive()) throw infrastructure("Owned runtime process tree did not terminate");
|
||||
var values = new LinkedHashMap<String, Object>(); values.put("sessionId", sessionId);
|
||||
values.putAll(mapper.convertValue(response, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {}));
|
||||
updateObservation(value -> value.transition(RuntimeObservation.Lifecycle.TERMINATED, "shutdown",
|
||||
Map.of("shutdown", mapper.convertValue(response, Object.class), "processTreeTerminated", true)));
|
||||
values.put("buildId", buildId); values.put("observation", observed);
|
||||
return new TaskTools.HeadlessReply(values, null);
|
||||
}
|
||||
terminate();
|
||||
if (alive()) throw infrastructure("Owned runtime process tree did not terminate");
|
||||
return new TaskTools.HeadlessReply(Map.of("sessionId", sessionId), null);
|
||||
return terminatedReply("cleanup_confirmed");
|
||||
} catch (AutomationException refusal) {
|
||||
rememberFailure("shutdown", refusal.failure());
|
||||
if (refusal.failure().code() == AutomationFailure.Code.MEMCARD_ERROR) {
|
||||
closing = false; throw new CompletionException(refusal);
|
||||
closing = false; throw new CompletionException(observedFailure(refusal));
|
||||
}
|
||||
abort("Headless shutdown failed"); throw infrastructure("Headless shutdown failed; owned process tree terminated; save publication outcome unknown");
|
||||
abort(refusal.failure()); throw new CompletionException(observedFailure(refusal));
|
||||
} catch (Exception failure) {
|
||||
abort("Headless shutdown failed"); throw infrastructure("Headless shutdown failed; owned process tree terminated; save publication outcome unknown");
|
||||
var cause = infrastructure("Headless shutdown failed; save publication outcome unknown", "cleanup");
|
||||
rememberFailure("shutdown", cause.failure()); abort(cause.failure()); throw cause;
|
||||
}
|
||||
});
|
||||
return shutdown;
|
||||
@@ -259,7 +338,16 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
private JsonNode request(String command, JsonNode params, Consumer<TrackedOperation.Progress> observer, long timeout) throws Exception {
|
||||
var item = new Pending(command, null, observer); send(item, params);
|
||||
try { return await(item.result, timeout); }
|
||||
catch (InterruptedException interrupted) { abort("Headless request interrupted"); Thread.currentThread().interrupt(); throw infrastructure("Headless request interrupted"); }
|
||||
catch (InterruptedException interrupted) {
|
||||
if(Set.of("get_logs","get_state","get_fault","capture","get_memcard_state").contains(command)) {
|
||||
// Complete an already sent read before cooperative cancellation. It cannot
|
||||
// mutate the guest; losing this response is never a reason to replay advance.
|
||||
try { awaitUninterruptibly(item.result,timeout); }
|
||||
finally { Thread.currentThread().interrupt(); }
|
||||
throw interrupted;
|
||||
}
|
||||
abort("Headless request interrupted"); Thread.currentThread().interrupt(); throw infrastructure("Headless request interrupted");
|
||||
}
|
||||
catch (TimeoutException exceeded) {
|
||||
if (!command.equals("shutdown") && !command.equals("initialize") && !dead.get()) {
|
||||
closing = true;
|
||||
@@ -268,11 +356,16 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
awaitUninterruptibly(stop.result, limits.shutdownTimeoutMs());
|
||||
} catch (Exception ignored) { /* Deadline escalation below always invalidates this process. */ }
|
||||
}
|
||||
abort("Headless request deadline exceeded"); throw infrastructure("Headless request deadline exceeded");
|
||||
var failure = infrastructure("Headless request deadline exceeded", "deadline");
|
||||
abort(failure.failure()); throw failure;
|
||||
}
|
||||
}
|
||||
private void send(Pending item, JsonNode params) {
|
||||
private synchronized void send(Pending item, JsonNode params) {
|
||||
if (dead.get()) throw infrastructure("Headless session lost; create a new session explicitly");
|
||||
if (closing && Set.of("get_state", "get_memcard_state", "capture").contains(item.command))
|
||||
throw new AutomationException(AutomationFailure.Code.BUSY, "Observation unavailable during shutdown");
|
||||
updateObservation(value -> value.withContext(Map.of("runtimeRequestId", item.id, "runtimeCommand", item.command)));
|
||||
if (item.frames != null) updateObservation(value -> value.withContext(Map.of("advanceRequestId", item.id)));
|
||||
var envelope = mapper.createObjectNode().put("requestId", item.id).put("command", item.command); envelope.set("params", params);
|
||||
final byte[] bytes;
|
||||
try { bytes = mapper.writeValueAsBytes(envelope); } catch (IOException invalid) { throw new IllegalArgumentException(invalid); }
|
||||
@@ -299,14 +392,21 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
}
|
||||
if (bytes.size() != 0) throw invalid("Truncated JSONL response");
|
||||
if (!closing || !pending.isEmpty()) abort("Headless stdout closed");
|
||||
} catch (Exception failure) { abort("Malformed or lost headless output"); }
|
||||
} catch (Exception failure) {
|
||||
var cause = failure instanceof AutomationException domain ? domain.failure()
|
||||
: new AutomationFailure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Malformed or lost headless output",
|
||||
Map.of(), Map.of("failureKind", failure instanceof com.fasterxml.jackson.core.JsonProcessingException
|
||||
|| failure instanceof java.nio.charset.CharacterCodingException ? "protocol" : "transport"));
|
||||
abort(cause);
|
||||
}
|
||||
}
|
||||
private void receive(JsonNode message) {
|
||||
process.descendants().forEach(descendants::add);
|
||||
if (message == null || !message.isObject()) throw invalid("Expected object");
|
||||
if (sessionId == null) {
|
||||
if (!text(message, "type").equals("hello")) throw invalid("Expected hello");
|
||||
sessionId = text(message, "sessionId"); greeting.complete(message); return;
|
||||
sessionId = text(message, "sessionId"); updateObservation(value -> RuntimeObservation.unknown(sessionId, buildId));
|
||||
greeting.complete(message); return;
|
||||
}
|
||||
if (!text(message, "sessionId").equals(sessionId)) throw invalid("Wrong session identity");
|
||||
var item = pending.get(text(message, "requestId"));
|
||||
@@ -314,7 +414,9 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
if (text(message, "type").equals("progress")) {
|
||||
long requested = count(message, "requested"), completed = count(message, "completed");
|
||||
if (item.frames == null || requested != item.frames || completed < item.completed || completed > requested) throw invalid("Invalid progress");
|
||||
item.completed = completed; item.observer.accept(new TrackedOperation.Progress(requested, completed)); return;
|
||||
item.completed = completed;
|
||||
updateObservation(value -> value.withProgress(new TrackedOperation.Progress(requested, completed)));
|
||||
item.observer.accept(new TrackedOperation.Progress(requested, completed)); return;
|
||||
}
|
||||
if (!text(message, "type").equals("response") || message.has("result") == message.has("error")) throw invalid("Invalid response envelope");
|
||||
if (message.has("error")) {
|
||||
@@ -354,10 +456,15 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
void abort(String message) {
|
||||
abort(new AutomationFailure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, message,
|
||||
Map.of(), Map.of("failureKind", "transport")));
|
||||
}
|
||||
private void abort(AutomationFailure cause) {
|
||||
if (dead.compareAndSet(false, true)) {
|
||||
updateObservation(value -> value.transition(RuntimeObservation.Lifecycle.LOST, "process_supervisor", Map.of()));
|
||||
terminate();
|
||||
greeting.completeExceptionally(infrastructure(message));
|
||||
pending.values().forEach(item -> item.result.completeExceptionally(infrastructure(message))); pending.clear();
|
||||
greeting.completeExceptionally(new AutomationException(cause));
|
||||
pending.values().forEach(item -> item.result.completeExceptionally(new AutomationException(cause))); pending.clear();
|
||||
} else terminate();
|
||||
}
|
||||
private void terminate() {
|
||||
@@ -377,9 +484,71 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
}
|
||||
}
|
||||
private void invalidateMalformed(AutomationException failure) {
|
||||
if (failure.getMessage().startsWith("Invalid headless response:")) abort("Invalid headless response");
|
||||
if ("protocol".equals(failure.failure().details().get("failureKind"))) abort(failure.failure());
|
||||
}
|
||||
private static AutomationException infrastructure(String message) { return infrastructure(message, "transport"); }
|
||||
private static AutomationException infrastructure(String message, String kind) {
|
||||
return new AutomationException(new AutomationFailure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,
|
||||
message, Map.of(), Map.of("failureKind", kind)));
|
||||
}
|
||||
private RuntimeObservation.Lifecycle currentLifecycle() {
|
||||
return observed.lifecycle() == RuntimeObservation.Lifecycle.UNBOOTED
|
||||
? RuntimeObservation.Lifecycle.UNBOOTED : RuntimeObservation.Lifecycle.GUEST_OBSERVED;
|
||||
}
|
||||
private void observeState(JsonNode result, RuntimeObservation.Lifecycle lifecycle, String source) {
|
||||
state(result);
|
||||
updateObservation(value -> value.transition(lifecycle, source, Map.of("state", mapper.convertValue(result, Object.class))));
|
||||
}
|
||||
private void observeMemcard(JsonNode result, String source) {
|
||||
HeadlessMemcard.state(result);
|
||||
updateObservation(value -> value.transition(value.lifecycle(), source, Map.of("memcard", mapper.convertValue(result, Object.class))));
|
||||
}
|
||||
private void rememberFailure(String source, AutomationFailure failure) {
|
||||
var facts = new LinkedHashMap<String, Object>();
|
||||
if (!failure.runtimeError().isEmpty()) {
|
||||
facts.put("error", failure.runtimeError());
|
||||
var details = failure.runtimeError().get("details");
|
||||
if (details instanceof Map<?, ?> detail && detail.get("state") instanceof Map<?, ?>)
|
||||
facts.put("memcard", detail.get("state"));
|
||||
} else facts.put("consumerFailure", Map.of("code", failure.code().name(), "message", failure.message(), "details", failure.details()));
|
||||
updateObservation(value -> value.transition(value.lifecycle(), source, facts));
|
||||
}
|
||||
private AutomationException observedFailure(AutomationException failure) {
|
||||
var original = failure.failure();
|
||||
return new AutomationException(new AutomationFailure(original.code(), original.message(), original.runtimeError(), original.details(), observed));
|
||||
}
|
||||
private void inspectAfterAdvance(boolean mediaRequired) {
|
||||
if (closing) {
|
||||
var failure = new AutomationFailure(AutomationFailure.Code.BUSY, "Session shutdown is in progress",
|
||||
Map.of(), Map.of("failureKind", "observation", "phase", "shutdown"));
|
||||
updateObservation(value -> value.unavailable("get_state", failure));
|
||||
if (mediaRequired) updateObservation(value -> value.unavailable("get_memcard_state", failure));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
observeState(request("get_state", mapper.createObjectNode(), null, limits.callTimeoutMs()), currentLifecycle(), "get_state");
|
||||
} catch (Exception failure) { inspectionFailed("get_state", failure); }
|
||||
if (mediaRequired) {
|
||||
try { observeMemcard(request("get_memcard_state", mapper.createObjectNode(), null, limits.callTimeoutMs()), "get_memcard_state"); }
|
||||
catch (Exception failure) { inspectionFailed("get_memcard_state", failure); }
|
||||
}
|
||||
}
|
||||
private void inspectionFailed(String source, Exception failure) {
|
||||
if (failure instanceof AutomationException domain) {
|
||||
invalidateMalformed(domain); updateObservation(value -> value.unavailable(source, domain.failure()));
|
||||
} else updateObservation(value -> value.unavailable(source, infrastructure("Observation unavailable", "observation").failure()));
|
||||
}
|
||||
private TaskTools.HeadlessReply terminatedReply(String source) {
|
||||
updateObservation(value -> value.transition(RuntimeObservation.Lifecycle.TERMINATED, source, Map.of("processTreeTerminated", true)));
|
||||
return new TaskTools.HeadlessReply(Map.of("sessionId", sessionId, "buildId", buildId, "observation", observed), null);
|
||||
}
|
||||
private synchronized void updateObservation(java.util.function.UnaryOperator<RuntimeObservation> update) {
|
||||
var next = update.apply(observed);
|
||||
// Progress/state completion can race process exit. A late observation cannot
|
||||
// resurrect availability; confirmed cleanup is a separate explicit transition.
|
||||
observed = dead.get() && next.lifecycle() != RuntimeObservation.Lifecycle.TERMINATED
|
||||
? next.transition(RuntimeObservation.Lifecycle.LOST, next.source(), Map.of()) : next;
|
||||
}
|
||||
private static AutomationException infrastructure(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, message); }
|
||||
private static <T> T await(CompletableFuture<T> future, long timeout) throws Exception {
|
||||
try { return future.get(timeout, TimeUnit.MILLISECONDS); }
|
||||
catch (ExecutionException error) { if (error.getCause() instanceof Exception cause) throw cause; throw error; }
|
||||
|
||||
@@ -33,6 +33,30 @@ final class HeadlessWire {
|
||||
for (var item : value) { if (!item.isTextual()) throw invalid("Invalid capability"); actual.add(item.textValue()); }
|
||||
if (!actual.containsAll(CAPABILITIES)) throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Required headless capability unavailable");
|
||||
}
|
||||
static GuestTests.LogPage logs(JsonNode value, String session, BigInteger after, int limit) {
|
||||
try {
|
||||
if (!text(value, "sessionId").equals(session) || !value.path("events").isArray()
|
||||
|| value.path("events").size() > limit || !value.path("gap").isBoolean() || !value.path("overflow").isBoolean())
|
||||
throw invalid("Invalid native log page identity/types");
|
||||
var events = new ArrayList<GuestTests.LogEvent>();
|
||||
for (var event : value.path("events")) {
|
||||
Long app = event.path("appId").isNull() ? null : uint(event.path("appId")).longValueExact();
|
||||
if (!event.has("appId") || !event.path("message").isTextual()) throw invalid("Invalid native log source/message");
|
||||
events.add(new GuestTests.LogEvent(uint(event.path("sequence")), uint(event.path("frame")), uint(event.path("timestampMs")),
|
||||
text(event,"level"), text(event,"source"), app, uint(event.path("tag")).intValueExact(), event.path("message").textValue()));
|
||||
}
|
||||
var next = nullableUint(value, "nextAfterSequence");
|
||||
if (!Objects.equals(next, events.isEmpty() ? after : events.getLast().sequence())
|
||||
|| !events.isEmpty() && after != null && events.getFirst().sequence().compareTo(after) <= 0)
|
||||
throw invalid("Native log cursor did not advance correctly");
|
||||
return new GuestTests.LogPage(session, uint(value.path("logEpoch")), events, nullableUint(value,"oldestSequence"),
|
||||
nullableUint(value,"newestSequence"), next, value.path("gap").booleanValue(), value.path("overflow").booleanValue());
|
||||
} catch (IllegalArgumentException | ArithmeticException malformed) { throw invalid("Invalid lossless native log values"); }
|
||||
}
|
||||
private static BigInteger nullableUint(JsonNode value, String key) {
|
||||
if (!value.has(key)) throw invalid("Missing " + key);
|
||||
return value.path(key).isNull() ? null : uint(value.path(key));
|
||||
}
|
||||
static void state(JsonNode value) {
|
||||
for (var key : List.of("pc", "logicalFrameIndex", "tickIndex", "appId")) uint(value.path(key));
|
||||
if (!Set.of("running", "paused", "terminated", "faulted").contains(text(value, "status")) || !value.path("stackTop").isArray()) throw invalid("Invalid state");
|
||||
@@ -104,5 +128,7 @@ final class HeadlessWire {
|
||||
if (number < 1 || number > Integer.MAX_VALUE) throw invalid("Invalid dimension");
|
||||
return (int) number;
|
||||
}
|
||||
static AutomationException invalid(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Invalid headless response: " + message); }
|
||||
static AutomationException invalid(String message) { return new AutomationException(new AutomationFailure(
|
||||
AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Invalid headless response: " + message,
|
||||
Map.of(), Map.of("failureKind", "protocol"))); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"profiles": [
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "macos-arm64-cli-0.1.0-18423f7-glyph-scene-v1",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-capacity-boundaries.json",
|
||||
"evidenceSha256": "d5b4576e697f6bcc489ce1795a86d2a365c03cd98ba73b88649ee5e2abaf4cd6"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-capacity-boundaries.json",
|
||||
"evidenceSha256": "d5b4576e697f6bcc489ce1795a86d2a365c03cd98ba73b88649ee5e2abaf4cd6"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"prometeu-headless": "18423f798ab28bbd38c12a7ee46459f3ef3d08876cc64327952f57be041fc5df",
|
||||
"prometeu-runtime": "ee00a587eb48030d1455d3c9bedd784ab620309a09877b50fe3641ae502635df"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+1607
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -46,6 +46,61 @@ class DevDesktopTest {
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
}
|
||||
|
||||
@Test void visualEvidenceInspectorShowsSharedMetricsExactPixelsAndExplicitBaselineReview() throws Exception {
|
||||
root=root.toRealPath();var pool=Executors.newSingleThreadExecutor();
|
||||
var authority=new DefaultAutomationSession(root,new ExecutorOperationExecutor(pool));
|
||||
var projects=new p.studio.core.project.ProjectAccessRegistry();projects.register(root,authority::enterManual,()->!authority.snapshot().closed(),authority);
|
||||
var codec=new p.studio.app.evidence.PngEvidenceCodec();var mapper=new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
var tools=new p.studio.core.session.DefaultEvidenceTools(projects,null,new p.studio.app.evidence.FileEvidenceStore(mapper),codec);
|
||||
byte[] original={10,20,30,0,40,50,60,(byte)255,70,80,90,(byte)255,1,2,3,(byte)255,4,5,6,(byte)255,7,8,9,(byte)255};
|
||||
Path expectedFile=root.resolve("expected.png"),actualFile=root.resolve("actual.png");
|
||||
Files.write(expectedFile,codec.encode(new Evidence.Pixels(3,2,original)));var changed=original.clone();changed[20]=8;
|
||||
Files.write(actualFile,codec.encode(new Evidence.Pixels(3,2,changed)));
|
||||
var expected=tools.importReference(root,null,"expected",expectedFile,null).artifacts().getFirst();
|
||||
var actual=tools.importReference(root,null,"actual",actualFile,null).artifacts().getFirst();
|
||||
var report=tools.compare(root,null,"desktop-comparison",expected.id(),actual.id(),Evidence.Parameters.exact(Evidence.Alpha.compare));
|
||||
assertEquals(1,report.report().differentPixels());
|
||||
var registry=new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(mapper),mapper,p.studio.app.mcp.McpEvidenceTools.handlers(tools,mapper));
|
||||
var inspector=new EvidenceInspector[1];var stage=new Stage[1];
|
||||
try {
|
||||
fx(()->{inspector[0]=new EvidenceInspector(root,authority,tools);stage[0]=new Stage();stage[0].setTitle("Visual checkpoint evidence qualification");
|
||||
var scroll=new ScrollPane(inspector[0]);scroll.setFitToWidth(true);stage[0].setScene(new Scene(scroll,1100,850));stage[0].show();inspector[0].refresh();});
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);var ready=new java.util.concurrent.atomic.AtomicBoolean();
|
||||
while(!ready.get()&&System.nanoTime()<deadline){fx(()->{var facts=(TextArea)inspector[0].lookup("#evidence-facts");ready.set(facts.getText().contains("Different pixels: 1"));});Thread.sleep(10);}
|
||||
assertTrue(ready.get());
|
||||
fx(()->{
|
||||
assertNotNull(inspector[0].lookup("#evidence-expected"));assertNotNull(inspector[0].lookup("#evidence-actual"));assertNotNull(inspector[0].lookup("#evidence-diff"));
|
||||
assertEquals("Expected (0, 0) RGBA = 10, 20, 30, 0",EvidenceInspector.pixelText("Expected",new Evidence.Pixels(3,2,original),0,0));
|
||||
var preview=inspector[0].lookup("#evidence-expected");
|
||||
var pointer=preview.localToScene(8,8);
|
||||
preview.fireEvent(new javafx.scene.input.MouseEvent(javafx.scene.input.MouseEvent.MOUSE_MOVED,
|
||||
pointer.getX(),pointer.getY(),8,8,javafx.scene.input.MouseButton.NONE,0,false,false,false,false,false,false,false,false,false,false,
|
||||
new javafx.scene.input.PickResult(preview,pointer.getX(),pointer.getY())));
|
||||
assertTrue(((Label)inspector[0].lookup("#evidence-pixel")).getText().contains("RGBA = 10, 20, 30, 0"));
|
||||
var approve=(Button)inspector[0].lookup("#evidence-approve-baseline");assertFalse(approve.isDisabled());
|
||||
// The desktop action requires an explicit confirmation before invoking the manual service.
|
||||
Platform.runLater(()->{for(var window:java.util.List.copyOf(javafx.stage.Window.getWindows()))if(window.getScene()!=null&&window.getScene().getRoot() instanceof DialogPane pane)
|
||||
((Button)pane.lookupButton(ButtonType.OK)).fire();});
|
||||
approve.fire();
|
||||
});
|
||||
deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);
|
||||
while(tools.list(root,null).stream().noneMatch(p->p.baseline()!=null)&&System.nanoTime()<deadline)Thread.sleep(10);
|
||||
var baseline=tools.list(root,null).stream().filter(p->p.baseline()!=null).findFirst().orElseThrow();assertEquals(expected.id(),baseline.baseline().artifactId());
|
||||
authority.grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);String task=authority.acquire().task().value();
|
||||
var arguments=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("limit",100);
|
||||
var wire=registry.call("studio_evidence_list",arguments).wire().path("structuredContent").path("value").path("publications");
|
||||
var mcpReport=java.util.stream.StreamSupport.stream(wire.spliterator(),false).filter(p->p.path("id").asText().equals(report.id())).findFirst().orElseThrow().path("report");
|
||||
assertEquals(mapper.valueToTree(report.report()),mcpReport);
|
||||
fx(()->{
|
||||
inspector[0].setManual(false);assertTrue(((Button)inspector[0].lookup("#evidence-approve-baseline")).isDisabled());
|
||||
assertFalse(((ComboBox<?>)inspector[0].lookup("#evidence-publications")).isDisabled());
|
||||
var image=stage[0].getScene().snapshot(null);var buffer=new java.awt.image.BufferedImage((int)image.getWidth(),(int)image.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
for(int y=0;y<buffer.getHeight();y++)for(int x=0;x<buffer.getWidth();x++)buffer.setRGB(x,y,image.getPixelReader().getArgb(x,y));
|
||||
try{Path file=Path.of("build/evidence-qualification/inspector.png");Files.createDirectories(file.getParent());javax.imageio.ImageIO.write(buffer,"png",file.toFile());}catch(Exception e){throw new RuntimeException(e);}
|
||||
});
|
||||
}finally{fx(()->{if(stage[0]!=null)stage[0].close();});authority.closeAsync().toCompletableFuture().join();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
@Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception {
|
||||
var pool = Executors.newSingleThreadExecutor();
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
|
||||
@@ -124,7 +179,8 @@ class DevDesktopTest {
|
||||
var pane = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane[1]; var window = new Stage[1];
|
||||
try {
|
||||
fx(() -> {
|
||||
pane[0] = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane(root);
|
||||
pane[0] = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane(root,
|
||||
origin -> p.studio.core.project.DiagnosticNavigation.read(root, origin));
|
||||
var view = p.studio.utilities.json.DiagnosticPayloads.view(java.util.List.of(value), "build", "failed", java.util.List.of(), "partial");
|
||||
pane[0].show(java.util.Map.of("issues", view.issues(), "summary", view.summary(), "context", java.util.Map.of()));
|
||||
window[0] = new Stage(); window[0].setTitle("Explained diagnostics desktop qualification");
|
||||
|
||||
@@ -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(24, tools.size());
|
||||
org.junit.jupiter.api.Assertions.assertEquals(48, 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());
|
||||
|
||||
+8
-5
@@ -57,13 +57,16 @@ class AnimationInstalledRuntimeTest {
|
||||
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.core.shipper.CompilerBuildGateway compiler=new p.studio.core.shipper.CompilerBuildGateway(){
|
||||
public CompilerBuildOutput compile(p.studio.api.project.ProjectReference project,java.util.function.Consumer<String> sink){return compile(project,p.studio.api.automation.BuildSelection.productionBuild(),project.rootPath().resolve("build"),sink);}
|
||||
public CompilerBuildOutput compile(p.studio.api.project.ProjectReference project,p.studio.api.automation.BuildSelection selection,Path output,java.util.function.Consumer<String> sink){
|
||||
var admitted=new p.studio.app.compiler.CompilerBuildGatewayAdapter(f.layouts).compile(project,selection,output,sink);
|
||||
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,project.rootPath().toString(),"core-v1",p.studio.compiler.utilities.SourceProviderFactory.filesystem(),selection.targetId(),output));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);
|
||||
return new p.studio.core.shipper.CompilerBuildGateway.CompilerBuildOutput(context.bytecodeArtifactPath,context.irBackend.getReservedMetadata().requiredCapabilities().asList(),admitted.issues(),admitted.context());
|
||||
}};
|
||||
var build=new StudioShipperService(compiler,f.packer.workspaceService(),f.mapper,new ExecutorOperationExecutor(workers)).withAssetPreflight(new p.studio.app.assets.AssetBudgetInspection(f.mapper,f.packer.workspaceService(),ignored->new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null))).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);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package p.studio.app.animation;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.StackPane;
|
||||
import javafx.stage.Stage;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import p.studio.app.StudioApplicationConfiguration;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.bank.AssetBankCompositionSessionFactory;
|
||||
import p.studio.api.assets.metadata.AssetMetadataService;
|
||||
import p.studio.api.assets.schema.AssetColorSchemaFactory;
|
||||
import p.studio.api.assets.scene.SceneBankWorkflow;
|
||||
import p.studio.api.assets.tiled.TiledAssetService;
|
||||
import p.studio.api.project.ProjectCatalog;
|
||||
import p.studio.api.session.ProjectSessionFactory;
|
||||
import p.studio.ui.javafx.events.StudioEventBus;
|
||||
import p.studio.ui.javafx.utilities.ThemeService;
|
||||
import p.studio.ui.javafx.utilities.i18n.I18nService;
|
||||
import p.studio.ui.javafx.workspaces.assets.AssetWorkspace;
|
||||
import java.nio.file.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Supplier;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual Assets controls, shared preview/publication, capacity projection and grant inspection. */
|
||||
class AssetAuthoringDesktopTest {
|
||||
@TempDir Path root;
|
||||
@BeforeAll static void toolkit()throws Exception {
|
||||
var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(10,TimeUnit.SECONDS);
|
||||
}
|
||||
@AfterAll static void toolkitStop(){Platform.exit();}
|
||||
static <T>T fx(Supplier<T> work)throws Exception {
|
||||
var value=new CompletableFuture<T>();Platform.runLater(()->{try{value.complete(work.get());}catch(Throwable failure){value.completeExceptionally(failure);}});return value.get(10,TimeUnit.SECONDS);
|
||||
}
|
||||
interface Check { boolean get()throws Exception; }
|
||||
static void await(Check check)throws Exception{long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);while(!check.get()){if(System.nanoTime()>end)fail("Assets flow did not finish");Thread.sleep(15);}}
|
||||
@Test void inspectExistingListCompositionSelectionAndPerBankCapacity()throws Exception {
|
||||
var fixture=new AnimationIntegrationTest();fixture.root=root;fixture.setup();root=fixture.root;
|
||||
var app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(false).run();
|
||||
var project=app.getBean(ProjectSessionFactory.class).open(app.getBean(ProjectCatalog.class).openProject(root));
|
||||
var window=new Stage[1];var workspace=new AssetWorkspace[1];
|
||||
try {
|
||||
fx(()->{
|
||||
var theme=app.getBean(ThemeService.class);
|
||||
workspace[0]=new AssetWorkspace(project.projectReference(),app.getBean(StudioEventBus.class),app.getBean(I18nService.class),
|
||||
app.getBean("studioExecutor",ExecutorService.class),theme,app.getBean(AssetCatalog.class),app.getBean(AssetCommands.class),
|
||||
app.getBean(AssetPacking.class),app.getBean(AssetDetails.class),app.getBean(AssetCreationCatalog.class),app.getBean(AssetMetadataService.class),
|
||||
app.getBean(AssetWorkspaceStorage.class),app.getBean(AssetCapacityPolicy.class),app.getBean(AssetBankCompositionSessionFactory.class),
|
||||
app.getBean(AssetColorSchemaFactory.class),app.getBean(TiledAssetService.class),app.getBean(SceneBankWorkflow.class));
|
||||
workspace[0].setAnimationService(app.getBean(p.studio.api.assets.animation.AnimationService.class));
|
||||
workspace[0].lifecycleParticipants().forEach(p->p.subscribe());
|
||||
window[0]=new Stage();window[0].setTitle("Assets authoring baseline");
|
||||
var scene=new Scene(new StackPane(workspace[0].rootNode()),1280,960);scene.getStylesheets().add(theme.getDefaultTheme());window[0].setScene(scene);window[0].show();workspace[0].load();return null;
|
||||
});
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(15);boolean selected=false,ready=false;
|
||||
while(!ready&&System.nanoTime()<end) {
|
||||
if(!selected)selected=fx(()->{
|
||||
var row=workspace[0].rootNode().lookup(".assets-workspace-asset-row");if(row==null)return false;
|
||||
row.fireEvent(new javafx.scene.input.MouseEvent(javafx.scene.input.MouseEvent.MOUSE_CLICKED,0,0,0,0,javafx.scene.input.MouseButton.PRIMARY,1,
|
||||
false,false,false,false,false,false,false,false,false,false,null));return true;
|
||||
});
|
||||
if(selected)ready=fx(()->workspace[0].rootNode().lookup(".assets-details-bank-composition-body")!=null);
|
||||
Thread.sleep(10);
|
||||
}
|
||||
assertTrue(ready,"Existing bank composition must finish loading before recording layout");
|
||||
fx(()->{
|
||||
workspace[0].rootNode().applyCss();((javafx.scene.Parent)workspace[0].rootNode()).layout();
|
||||
assertFalse(workspace[0].rootNode().lookupAll(".assets-workspace-action-button").isEmpty());
|
||||
var snapshot=window[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{Path destination=Path.of("build/asset-authoring-qualification/assets-before.png");Files.createDirectories(destination.getParent());javax.imageio.ImageIO.write(image,"png",destination.toFile());}
|
||||
catch(Exception failure){throw new RuntimeException(failure);}return null;
|
||||
});
|
||||
var details=app.getBean(AssetDetails.class).get(project.projectReference(),app.getBean(AssetCatalog.class).list(project.projectReference(),false).getFirst().reference());
|
||||
assertEquals(3,details.bankComposition().selectedFiles().size());
|
||||
fx(()->{
|
||||
window[0].setWidth(1800);window[0].setHeight(1050);
|
||||
var split=(SplitPane)workspace[0].rootNode().lookup(".split-pane");if(split!=null)split.setDividerPositions(0.2);
|
||||
workspace[0].rootNode().applyCss();((javafx.scene.Parent)workspace[0].rootNode()).layout();
|
||||
var bank=workspace[0].rootNode().lookup(".assets-details-bank-composition-body");
|
||||
javafx.scene.Node parent=bank;while(parent!=null&&!(parent instanceof ScrollPane))parent=parent.getParent();
|
||||
if(parent instanceof ScrollPane scroll) {
|
||||
double y=bank.localToScene(0,0).getY()-scroll.getContent().localToScene(0,0).getY();
|
||||
double range=scroll.getContent().getLayoutBounds().getHeight()-scroll.getViewportBounds().getHeight();
|
||||
if(range>0)scroll.setVvalue(Math.max(0,Math.min(1,(y-45)/range)));
|
||||
}
|
||||
return null;
|
||||
});
|
||||
fx(()->{
|
||||
var snapshot=window[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("build/asset-authoring-qualification/assets-composition-before.png").toFile());}
|
||||
catch(Exception failure){throw new RuntimeException(failure);}return null;
|
||||
});
|
||||
|
||||
fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.save(fixture.project,fixture.uuid,null,fixture.document()));
|
||||
var authoring=app.getBean(AssetAuthoringService.class);
|
||||
byte[] before=Files.readAllBytes(fixture.bankRoot.resolve("asset.json"));
|
||||
fx(()->{workspace[0].setAssetAuthoring(authoring);p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(workspace[0].rootNode(),()->project.automation().snapshot().manualAllowed());return null;});
|
||||
await(()->fx(()->((Label)workspace[0].rootNode().lookup("#assets-budget-summary")).getText().contains("glyph: existing 1")));
|
||||
fx(()->{
|
||||
javafx.scene.Node node=workspace[0].rootNode().lookup(".assets-details-bank-composition-body");while(!(node instanceof p.studio.ui.javafx.workspaces.assets.details.bank.AssetDetailsBankCompositionControl))node=node.getParent();
|
||||
var control=node;var i18n=app.getBean(I18nService.class);
|
||||
control.lookupAll(".button").stream().filter(n->n instanceof Button b&&b.getText().equals(i18n.text(p.studio.ui.javafx.utilities.i18n.I18n.FORM_ACTION_CHANGE))).map(n->(Button)n).findFirst().orElseThrow().fire();
|
||||
assertTrue(project.automation().snapshot().manualAllowed());var right=(ListView<?>)control.lookup(".studio-dual-list-right");assertFalse(right.isDisabled(),"Composition edit must enable selection");assertEquals(3,right.getItems().size());right.getSelectionModel().clearAndSelect(1);assertEquals(1,right.getSelectionModel().getSelectedIndex());
|
||||
var up=control.lookupAll(".button").stream().filter(n->n instanceof Button b&&b.getText().equals("Up")).map(n->(Button)n).findFirst().orElseThrow();assertFalse(up.isDisabled(),"Reorder is enabled for the selected row");up.fire();assertTrue(((p.studio.ui.javafx.controls.forms.StudioFormSection)control).hasUnsavedDraft(),"Reorder changes the draft");
|
||||
return null;
|
||||
});
|
||||
await(()->fx(()->{var control=workspace[0].rootNode().lookup(".assets-details-bank-composition-section");return control.lookupAll(".button").stream().anyMatch(n->n instanceof Button b&&b.getText().equals(app.getBean(I18nService.class).text(p.studio.ui.javafx.utilities.i18n.I18n.FORM_ACTION_APPLY))&&!b.isDisabled());}));
|
||||
fx(()->{var control=workspace[0].rootNode().lookup(".assets-details-bank-composition-section");control.lookupAll(".button").stream().filter(n->n instanceof Button b&&b.getText().equals(app.getBean(I18nService.class).text(p.studio.ui.javafx.utilities.i18n.I18n.FORM_ACTION_APPLY))).map(n->(Button)n).findFirst().orElseThrow().fire();return null;});
|
||||
await(()->fx(()->javafx.stage.Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#asset-batch-publish")!=null)));
|
||||
assertArrayEquals(before,Files.readAllBytes(fixture.bankRoot.resolve("asset.json")),"Review leaves published inputs intact");
|
||||
fx(()->{var review=javafx.stage.Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#asset-batch-rebind")!=null).findFirst().orElseThrow();assertTrue(((Button)review.getScene().lookup("#asset-batch-publish")).isDisabled());Platform.runLater(()->((Button)review.getScene().lookup("#asset-batch-rebind")).fire());return null;});
|
||||
await(()->fx(()->javafx.stage.Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#asset-rebind-preview")!=null)));
|
||||
fx(()->{var rebind=javafx.stage.Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#asset-rebind-preview")!=null).findFirst().orElseThrow();
|
||||
for(var node:rebind.getScene().getRoot().lookupAll(".combo-box"))if(node instanceof ComboBox<?> picker&&picker.getUserData() instanceof p.studio.api.assets.AssetBatches.Artifact from){for(int i=0;i<picker.getItems().size();i++)if(picker.getItems().get(i) instanceof p.studio.api.assets.AssetBatches.ArtifactInfo info&&info.identity().equals(from)){picker.getSelectionModel().select(i);break;}}
|
||||
assertFalse(((Button)rebind.getScene().lookup("#asset-rebind-preview")).isDisabled());((Button)rebind.getScene().lookup("#asset-rebind-preview")).fire();return null;});
|
||||
await(()->fx(()->javafx.stage.Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#asset-batch-publish") instanceof Button b&&!b.isDisabled())));
|
||||
|
||||
fx(()->{var review=javafx.stage.Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#asset-batch-publish")!=null).findFirst().orElseThrow();assertFalse(((TextArea)review.getScene().lookup("#asset-batch-preview")).getText().isBlank());((Button)review.getScene().lookup("#asset-batch-publish")).fire();return null;});
|
||||
await(()->fixture.mapper.readTree(fixture.bankRoot.resolve("asset.json").toFile()).path("artifacts").get(0).path("artifact_id").asText().equals("g1"));
|
||||
new p.animation.AnimationValidator().requireValid(new p.animation.AnimationCodec().decode(Files.readString(fixture.bankRoot.resolve("animations.studio.json"))),fixture.layouts.resolve(root,fixture.uuid));
|
||||
await(()->project.automation().snapshot().manualOperations()==0);
|
||||
assertTrue(project.automation().grant(false).toCompletableFuture().get(10,TimeUnit.SECONDS).success());var task=project.automation().acquire().task();
|
||||
fx(()->{workspace[0].manualAllowed(project.automation().snapshot().manualAllowed());assertTrue(workspace[0].rootNode().lookup("#assets-import-png").isDisable());assertFalse(workspace[0].rootNode().lookup("#assets-refresh-budget").isDisable());((Button)workspace[0].rootNode().lookup("#assets-refresh-budget")).fire();return null;});
|
||||
assertEquals(authoring.budget(root,null),authoring.budget(root,task.value()));
|
||||
fx(()->{var snapshot=window[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("build/asset-authoring-qualification/assets-after.png").toFile());}catch(Exception e){throw new RuntimeException(e);}return null;});
|
||||
project.automation().reclaim().toCompletableFuture().get(10,TimeUnit.SECONDS);
|
||||
} finally {
|
||||
fx(()->{if(workspace[0]!=null){workspace[0].unLoad();workspace[0].lifecycleParticipants().forEach(p->p.unsubscribe());}if(window[0]!=null)window[0].close();return null;});
|
||||
project.close();app.close();fixture.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package p.studio.app.animation;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.app.assets.FileAssetBatchWorkspace;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.core.assets.DefaultAssetAuthoringService;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.session.DefaultAutomationSession;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Real packer/filesystem composition behind the same human/task service. */
|
||||
class AssetBatchIntegrationTest {
|
||||
@TempDir Path root;
|
||||
AnimationIntegrationTest fixture;FileAssetBatchWorkspace disk;AssetAuthoringService service;
|
||||
ExecutorService workers;DefaultAutomationSession session;
|
||||
final AssetReference hero=AssetReference.forAssetId(1);
|
||||
@BeforeEach void open()throws Exception {
|
||||
fixture=new AnimationIntegrationTest();fixture.root=root;fixture.setup();root=fixture.root;
|
||||
workers=Executors.newFixedThreadPool(4);var operations=new ExecutorOperationExecutor(workers);
|
||||
session=new DefaultAutomationSession(root,operations);var projects=new ProjectAccessRegistry();projects.register(root,session::enterManual,()->true,session);
|
||||
disk=new FileAssetBatchWorkspace(fixture.mapper,fixture.packer.workspaceService(),new p.studio.app.assets.AssetBudgetInspection(fixture.mapper,fixture.packer.workspaceService(),p->new p.studio.api.project.ProjectLocalStudioSetup(null,null))::inspect);
|
||||
var catalog=new ProjectCatalogService(root.getParent(),fixture.mapper,new ProjectLocalStudioSetupStore(fixture.mapper));
|
||||
service=new DefaultAssetAuthoringService(projects,catalog,disk,operations);
|
||||
}
|
||||
@AfterEach void close(){try{if(session!=null)session.closeAsync().toCompletableFuture().join();}finally{if(workers!=null)workers.shutdownNow();if(fixture!=null)fixture.close();}}
|
||||
Request request(List<Mutation> changes,List<Rebind> rebinds){return new Request(service.revision(root,null),changes,rebinds,List.of());}
|
||||
String hash(Path path)throws Exception{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path)));}
|
||||
@Test void identicalReimportIsNoOpAndDurableCommitQueriesSurviveAReopenedAdapter()throws Exception {
|
||||
fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.save(fixture.project,fixture.uuid,null,fixture.document()));
|
||||
byte[] source=Files.readAllBytes(fixture.bankRoot.resolve("asset.json")),animation=Files.readAllBytes(fixture.bankRoot.resolve("animations.studio.json"));
|
||||
var input=new PngInput("assets/hero/g0.png",null,hash(fixture.bankRoot.resolve("g0.png")));
|
||||
var request=request(List.of(new ImportPng("same",input,hero,"g0.png")),List.of());
|
||||
var preview=service.preview(root,null,"same",request);assertEquals(PreviewState.no_op,preview.state(),preview.toString());
|
||||
assertEquals(preview,service.preview(root,null,"same",request));
|
||||
var result=service.commit(root,null,"commit",preview.batchId(),preview.revision());assertEquals(CommitState.no_op,result.state());
|
||||
assertEquals(result,service.commit(root,null,"commit",preview.batchId(),preview.revision()));
|
||||
assertArrayEquals(source,Files.readAllBytes(fixture.bankRoot.resolve("asset.json")));assertArrayEquals(animation,Files.readAllBytes(fixture.bankRoot.resolve("animations.studio.json")));
|
||||
var reopened=new FileAssetBatchWorkspace(fixture.mapper,fixture.packer.workspaceService(),p->{throw new UnsupportedOperationException();});
|
||||
assertEquals(result,reopened.result(fixture.project,null,preview.batchId()));
|
||||
}
|
||||
@Test void reorderRequiresEveryExplicitReferenceAndThenPublishesItsAnimationBindings()throws Exception {
|
||||
fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.save(fixture.project,fixture.uuid,null,fixture.document()));
|
||||
byte[] original=Files.readAllBytes(fixture.bankRoot.resolve("asset.json"));
|
||||
var changes=List.<Mutation>of(new ComposeBank("order",hero,List.of("g2.png","g1.png","g0.png")));
|
||||
var rejected=service.preview(root,null,"reject-order",request(changes,List.of()));assertEquals(PreviewState.rejected,rejected.state());assertFalse(rejected.affectedReferences().isEmpty());
|
||||
assertArrayEquals(original,Files.readAllBytes(fixture.bankRoot.resolve("asset.json")));
|
||||
var mappings=new ArrayList<Rebind>();var groups=new HashMap<Artifact,List<ReferenceUse>>();
|
||||
rejected.affectedReferences().forEach(reference->groups.computeIfAbsent(reference.target(),key->new ArrayList<>()).add(reference));
|
||||
groups.forEach((from,uses)->mappings.add(new Rebind(from,from,uses)));
|
||||
var accepted=service.preview(root,null,"rebind-order",request(changes,mappings));assertEquals(PreviewState.ready,accepted.state(),accepted.toString());
|
||||
var result=service.commit(root,null,"publish-order",accepted.batchId(),accepted.revision());assertTrue(result.applied());
|
||||
var document=new p.animation.AnimationCodec().decode(Files.readString(fixture.bankRoot.resolve("animations.studio.json")));
|
||||
var bank=fixture.layouts.resolve(root,fixture.uuid);new p.animation.AnimationValidator().requireValid(document,bank);
|
||||
assertEquals(2,document.bindings().stream().filter(b->b.artifactId().equals("g0")).findFirst().orElseThrow().glyphId());
|
||||
}
|
||||
|
||||
@Test void appendPreservesPublishedIdentitiesAndANewReplacementSurvivesAmendedPreview()throws Exception {
|
||||
fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.save(fixture.project,fixture.uuid,null,fixture.document()));
|
||||
var original=service.artifacts(root,null,hero);byte[] animation=Files.readAllBytes(fixture.bankRoot.resolve("animations.studio.json"));
|
||||
var append=List.<Mutation>of(new ImportPng("append",new PngInput("assets/hero/g0.png",null,hash(fixture.bankRoot.resolve("g0.png"))),hero,"g3.png"),new ComposeBank("compose",hero,List.of("g0.png","g1.png","g2.png","g3.png")));
|
||||
var preview=service.preview(root,null,"append",request(append,List.of()));assertTrue(preview.canCommit(),preview.toString());assertTrue(service.commit(root,null,"append-commit",preview.batchId(),preview.revision()).applied());
|
||||
assertEquals(original,service.artifacts(root,null,hero).subList(0,3));assertArrayEquals(animation,Files.readAllBytes(fixture.bankRoot.resolve("animations.studio.json")));
|
||||
// Propose a new artifact and replace an old referenced one in this same reviewed batch.
|
||||
var replace=List.<Mutation>of(new ImportPng("new",new PngInput("assets/hero/g0.png",null,hash(fixture.bankRoot.resolve("g0.png"))),hero,"g4.png"),new ComposeBank("replace",hero,List.of("g4.png","g1.png","g2.png","g3.png")));
|
||||
var rejected=service.preview(root,null,"replacement",request(replace,List.of()));assertEquals(PreviewState.rejected,rejected.state());
|
||||
var target=service.previewArtifacts(root,null,rejected.batchId(),hero).stream().filter(a->a.sourcePath().endsWith("g4.png")).findFirst().orElseThrow().identity();
|
||||
var grouped=new LinkedHashMap<Artifact,List<ReferenceUse>>();rejected.affectedReferences().forEach(use->grouped.computeIfAbsent(use.target(),ignored->new ArrayList<>()).add(use));
|
||||
var mappings=grouped.entrySet().stream().map(e->new Rebind(e.getKey(),e.getKey().artifactId().equals("g0")?target:e.getKey(),e.getValue())).toList();
|
||||
var accepted=service.preview(root,null,"replacement-reviewed",request(replace,mappings));assertTrue(accepted.canCommit(),accepted.toString());assertTrue(service.commit(root,null,"replacement-commit",accepted.batchId(),accepted.revision()).applied());
|
||||
new p.animation.AnimationValidator().requireValid(new p.animation.AnimationCodec().decode(Files.readString(fixture.bankRoot.resolve("animations.studio.json"))),fixture.layouts.resolve(root,fixture.uuid));
|
||||
}
|
||||
@Test void changedAuthorizedExternalPngIsRejectedBeforeCommit()throws Exception {
|
||||
Path external=Files.createTempFile("asset-source-",".png");
|
||||
try{Files.copy(fixture.bankRoot.resolve("g0.png"),external,StandardCopyOption.REPLACE_EXISTING);var grant=service.authorizePng(root,external);
|
||||
var preview=service.preview(root,null,"external",request(List.of(new ImportPng("external",new PngInput(null,grant.grantId(),grant.sha256()),hero,"external.png")),List.of()));assertTrue(preview.canCommit(),preview.toString());
|
||||
Files.copy(fixture.bankRoot.resolve("g1.png"),external,StandardCopyOption.REPLACE_EXISTING);var result=service.commit(root,null,"external-commit",preview.batchId(),preview.revision());assertEquals(CommitState.rejected,result.state());assertTrue(result.diagnostics().stream().anyMatch(d->d.code().equals("PNG_SOURCE_CHANGED")));assertFalse(Files.exists(fixture.bankRoot.resolve("external.png")));
|
||||
}finally{Files.deleteIfExists(external);}
|
||||
}
|
||||
@Test void staleRevisionAndChangedPngRefuseBeforePublication()throws Exception {
|
||||
var preview=service.preview(root,null,"preload",request(List.of(new UpdateContract("preload",hero,true,"NONE",Map.of(),Map.of("tile_size","16x16"))),List.of()));
|
||||
assertTrue(preview.canCommit(),preview.toString());
|
||||
Files.writeString(root.resolve("prometeu.json"),Files.readString(root.resolve("prometeu.json"))+"\n");
|
||||
byte[] before=Files.readAllBytes(fixture.bankRoot.resolve("asset.json"));
|
||||
var result=service.commit(root,null,"stale",preview.batchId(),preview.revision());assertEquals(CommitState.conflict,result.state());assertFalse(result.conflicts().isEmpty());
|
||||
assertArrayEquals(before,Files.readAllBytes(fixture.bankRoot.resolve("asset.json")));
|
||||
}
|
||||
@Test void authenticatedHttpToolsPublishGlyphSceneAndOwnershipThroughTheSharedService()throws Exception {
|
||||
var json=p.studio.app.assets.AssetBatchJson.mapper(fixture.mapper);
|
||||
var registry=new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(json),json,p.studio.app.mcp.McpAssetAuthoringTools.handlers(service,json));
|
||||
try(var server=new p.studio.app.mcp.LocalMcpServer(json,registry);var http=java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();var credential=server.credentials().prepare(root.toRealPath());credential.activate();
|
||||
assertTrue(session.grant(false).toCompletableFuture().get().success());String task=session.acquire().task().value();
|
||||
class Client {
|
||||
String connection;int sequence;
|
||||
com.fasterxml.jackson.databind.JsonNode post(String method,Object params)throws Exception {
|
||||
var message=json.createObjectNode().put("jsonrpc","2.0").put("id",++sequence).put("method",method);message.set("params",json.valueToTree(params));if(method.startsWith("notifications/"))message.remove("id");
|
||||
var request=java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(20)).header("Content-Type","application/json").header("Accept","application/json, text/event-stream").header("Authorization","Bearer "+credential.secret()).header("MCP-Protocol-Version",p.studio.app.mcp.LocalMcpServer.PROTOCOL_VERSION);
|
||||
if(connection!=null)request.header("Mcp-Session-Id",connection);
|
||||
var response=http.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(json.writeValueAsString(message))).build(),java.net.http.HttpResponse.BodyHandlers.ofString());if(method.startsWith("notifications/")){assertEquals(202,response.statusCode());return json.nullNode();}assertEquals(200,response.statusCode(),response.body());
|
||||
response.headers().firstValue("Mcp-Session-Id").ifPresent(value->connection=value);return json.readTree(response.body());
|
||||
}
|
||||
com.fasterxml.jackson.databind.JsonNode call(String name,Map<String,Object> args)throws Exception {
|
||||
var scoped=new LinkedHashMap<String,Object>(args);scoped.put("projectRoot",root.toString());scoped.put("taskId",task);
|
||||
var response=post("tools/call",Map.of("name",name,"arguments",scoped));if(response.has("error"))registry.call(name,json.valueToTree(scoped));assertFalse(response.has("error"),response.toString());var result=response.path("result");assertFalse(result.path("isError").asBoolean(),result.toString());return result.path("structuredContent").path("value");
|
||||
}
|
||||
Result publish(List<Mutation> mutations,List<Ownership> ownership)throws Exception {
|
||||
var revision=json.treeToValue(call("studio_assets_revision",Map.of()).path("revision"),Revision.class);
|
||||
var request=new Request(revision,mutations,List.of(),ownership);String requestId=UUID.randomUUID().toString();
|
||||
var value=call("studio_assets_preview",Map.of("clientRequestId",requestId,"request",request));var preview=json.treeToValue(value,Preview.class);assertTrue(preview.canCommit(),value.toString());
|
||||
assertEquals(value,call("studio_assets_preview",Map.of("clientRequestId",requestId,"request",request)));
|
||||
var committed=call("studio_assets_commit",Map.of("clientRequestId",UUID.randomUUID().toString(),"batchId",preview.batchId(),"expectedRevision",revision));var result=json.treeToValue(committed,Result.class);assertTrue(result.applied(),committed.toString());assertEquals(committed,call("studio_assets_result",Map.of("batchId",preview.batchId())));return result;
|
||||
}
|
||||
}
|
||||
var client=new Client();client.post("initialize",Map.of("protocolVersion",p.studio.app.mcp.LocalMcpServer.PROTOCOL_VERSION,"clientInfo",Map.of("name","asset-qualification","version","1"),"capabilities",Map.of()));client.post("notifications/initialized",Map.of());
|
||||
var bank=AssetReference.forRelativeAssetRoot("shared");var scene=AssetReference.forRelativeAssetRoot("shared-scene");
|
||||
client.publish(List.of(new CreateBank("create","shared","shared",AssetFamily.GLYPH_BANK,"GLYPH_INDEXED_V1","NONE",true),new UpdateContract("tile",bank,true,"NONE",Map.of(),Map.of("tile_size","16x16")),new ImportPng("png",new PngInput("assets/hero/g0.png",null,hash(fixture.bankRoot.resolve("g0.png"))),bank,"red.png"),new ComposePalettes("palette",bank,List.of(new Palette(0,List.of(0xff0000ffL)))),new ComposeBank("compose",bank,List.of("red.png"))),List.of());
|
||||
var artifact=service.artifacts(root,task,bank).getFirst();assertFalse(client.call("studio_assets_artifacts",Map.of("assetReference",bank.value())).path("artifacts").isEmpty());
|
||||
var layers=new ArrayList<SceneLayer>();layers.add(new SceneLayer(true,bank,16,1,1,1,1,List.of(new SceneTile(true,artifact.identity(),0,false,false))));for(int i=1;i<4;i++)layers.add(new SceneLayer(false,null,0,1,1,1,1,List.of(new SceneTile(false,null,0,false,false))));
|
||||
client.publish(List.of(new CreateBank("scene","shared-scene","shared-scene",AssetFamily.SCENE_BANK,"SCENE_TILED_V1","NONE",true),new ComposeScene("map",scene,layers)),List.of());
|
||||
var source=new PngInput("assets/hero/g0.png",null,hash(fixture.bankRoot.resolve("g0.png")));
|
||||
assertEquals(CommitState.no_op,client.publish(List.of(new ImportPng("same",source,bank,"red.png")),List.of()).state());
|
||||
client.publish(List.of(),List.of(new Ownership(bank,"assets/shared/red.png","selected PNG",List.of(hero),false)));
|
||||
assertEquals(1,client.call("studio_assets_dependencies",Map.of("assetReference",bank.value())).path("ownership").size());
|
||||
var budget=client.call("studio_assets_budget",Map.of());assertEquals("unknown",budget.path("qualification").path("state").asText());assertEquals(service.budget(root,null).revision().sha256(),budget.path("revision").path("sha256").asText());
|
||||
var manifest=(com.fasterxml.jackson.databind.node.ObjectNode)fixture.mapper.readTree(fixture.bankRoot.resolve("asset.json").toFile());((com.fasterxml.jackson.databind.node.ObjectNode)manifest.path("artifacts").get(1)).put("index",3);fixture.mapper.writeValue(fixture.bankRoot.resolve("asset.json").toFile(),manifest);
|
||||
var diagnostics=client.call("studio_assets_budget",Map.of()).path("diagnostics");assertTrue(diagnostics.toString().contains("GLYPH_INDICES_NONCONTIGUOUS"),diagnostics.toString());assertTrue(diagnostics.toString().contains("missingIndices"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void currentTaskAuthorityPrecedesDedupAndHumanMutationsAreBlockedDuringGrant()throws Exception {
|
||||
assertTrue(session.grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS).success());String task=session.acquire().task().value();
|
||||
var request=request(List.of(),List.of());var preview=service.preview(root,task,"task-preview",request);
|
||||
assertEquals(preview,service.preview(root,task,"task-preview",request));
|
||||
assertThrows(ControlDeniedException.class,()->service.preview(root,null,"human",request));
|
||||
var different=new Request(request.expectedRevision(),List.of(new BuildParticipation("exclude",hero,false)),List.of(),List.of());
|
||||
assertEquals(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,assertThrows(AutomationException.class,()->service.preview(root,task,"task-preview",different)).failure().code());
|
||||
session.reclaim().toCompletableFuture().get(5,TimeUnit.SECONDS);
|
||||
assertThrows(ControlDeniedException.class,()->service.preview(root,task,"task-preview",request));
|
||||
assertEquals(preview,service.preview(root,null,preview.batchId()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.metadata.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.core.assets.*;
|
||||
import p.studio.core.assets.metadata.AssetStudioMetadataService;
|
||||
import p.studio.core.assets.scene.SceneBankWorkflowService;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.core.shipper.StudioShipperService;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** Uses public asset commands on a disposable project; no private binary pack emitter. */
|
||||
public final class SmallAssetProject implements AutoCloseable {
|
||||
public final ObjectMapper json=new ObjectMapper();public final Path root;
|
||||
public final p.packer.Packer packer;public final ProjectReference project;
|
||||
public final PackerAssetCommands commands;public final PackerAssetCatalog catalog;
|
||||
public SmallAssetProject(Path root)throws Exception {
|
||||
this.root=Files.createDirectories(root).toRealPath();root=this.root;Files.createDirectories(root.resolve("src"));
|
||||
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"capacityfixture\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"app_id\":27301,\"dependencies\":[]}");
|
||||
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");Files.writeString(root.resolve("src/main.pbs"),"[Frame] fn frame() -> void {}\n");
|
||||
packer=p.packer.Packer.bootstrap(json,event->{});commands=new PackerAssetCommands(packer.workspaceService());catalog=new PackerAssetCatalog(packer.workspaceService());
|
||||
project=new ProjectCatalogService(root.getParent(),json,new ProjectLocalStudioSetupStore(json)).openProject(root);
|
||||
}
|
||||
public AssetReference glyph(String name,boolean preload)throws Exception {
|
||||
var created=commands.create(project,name,name,AssetFamily.GLYPH_BANK,"GLYPH_INDEXED_V1","NONE",preload);
|
||||
if(!created.successful())throw new IllegalStateException(created.summary());
|
||||
var configured=commands.updateContract(project,created.assetReference(),preload,"NONE",Map.of(),Map.of("tile_size","16x16"));
|
||||
if(!configured.success())throw new IllegalStateException(configured.errorMessage());
|
||||
var image=new java.awt.image.BufferedImage(16,16,java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,0xffff0000);
|
||||
javax.imageio.ImageIO.write(image,"png",created.assetRoot().resolve("red.png").toFile());
|
||||
var palette=commands.applyPaletteOverhauling(project,created.assetReference(),List.of(Map.of("index",0,"rgba8888",List.of(0xff0000ff))));
|
||||
if(!palette.success())throw new IllegalStateException(palette.errorMessage());
|
||||
var composition=commands.applyBankComposition(project,created.assetReference(),List.of("red.png"));if(!composition.success())throw new IllegalStateException(composition.errorMessage());
|
||||
return created.assetReference();
|
||||
}
|
||||
public AssetReference scene(String name,AssetReference glyph,boolean preload)throws Exception {
|
||||
var created=commands.create(project,name,name,AssetFamily.SCENE_BANK,"SCENE_TILED_V1","NONE",preload);
|
||||
if(!created.successful())throw new IllegalStateException(created.summary());
|
||||
var source=catalog.list(project,false).stream().filter(a->a.reference().equals(glyph)).findFirst().orElseThrow();
|
||||
var layers=new ArrayList<AssetStudioSceneLayerBinding>();
|
||||
for(int i=1;i<=4;i++)layers.add(new AssetStudioSceneLayerBinding(false,i,"Layer "+i,1,1,"scene.tmx",root.resolve("assets").relativize(source.root()).toString(),1,1,0,List.of(AssetStudioSceneTile.inactive(0))));
|
||||
var metadata=new AssetStudioSceneBankMetadata(1,1,4,layers,created.assetRoot().resolve("scene-bank.studio.json"));
|
||||
var write=new AssetStudioMetadataService(json).writeSceneBankMetadata(created.assetRoot(),metadata);if(!write.successful())throw new IllegalStateException(write.message());
|
||||
new SceneBankWorkflowService(catalog,json).writeComposition(project,created.assetRoot(),metadata);return created.assetReference();
|
||||
}
|
||||
public p.studio.api.shipper.ShipperPrepareResult build()throws Exception {
|
||||
try(var workers=Executors.newSingleThreadExecutor()) {
|
||||
return new StudioShipperService(new CompilerBuildGatewayAdapter(),packer.workspaceService(),json,new ExecutorOperationExecutor(workers))
|
||||
.prepare(project,event->{}).completion().toCompletableFuture().get(45,TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@Override public void close(){packer.close();}
|
||||
}
|
||||
@@ -21,9 +21,27 @@ public final class InstalledKnowledgeProbe {
|
||||
check(!Files.exists(Path.of("settings.gradle.kts")) && !Files.exists(Path.of("docs")), "No repository in working directory");
|
||||
verifyRuntimeCatalogs(provider.getClass().getClassLoader());
|
||||
if (arguments.length == 1 && arguments[0].equals("--catalog-only")) return;
|
||||
var guideType = Class.forName("p.studio.app.mcp.McpConnectionGuide");
|
||||
check(guideType.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "Lifecycle guide must come from installed JAR");
|
||||
var guide = (String)guideType.getField("INSTRUCTIONS").get(null);
|
||||
for (var requirement : java.util.List.of("studio_tests_start", "studio_tests_transcript", "disposable_reopen", "studio_evidence_persist", "studio_evidence_compare", "explicit alpha", "human manual-control", "studio_headless_reset", "same buildId", "Unknown completedFrames is null",
|
||||
"memcardChoice", "details.control", "clientRequestId", "studio_assets_preview", "studio_assets_commit", "studio_assets_result", "Sound is deferred"))
|
||||
check(guide.contains(requirement), "Missing installed recovery guidance: " + requirement);
|
||||
System.out.println("Installed lifecycle and recovery guide verified");
|
||||
Path root = Files.createDirectory(Path.of("example")).toRealPath();
|
||||
var docs = provider.documentation().orElseThrow().references(1, p.studio.AppMode.Game);
|
||||
verifySpecificationAliases(provider.getClass().getClassLoader(), docs);
|
||||
var assetGuide=docs.stream().filter(r->r.id().equals("pbs:example:game:1:asset-authoring/GUIDE.md")).findFirst().orElseThrow();
|
||||
for(var term:java.util.List.of("compose_palettes","SCENE_TILED_V1","affectedReferences","cartridge","Sound"))check(assetGuide.text().contains(term),"Missing installed asset guidance: "+term);
|
||||
try(var input=guideType.getClassLoader().getResourceAsStream("asset-capacity/catalog.json")) {
|
||||
check(input!=null,"Missing installed capacity catalog");var profile=new ObjectMapper().readTree(input).path("profiles").get(0).path("profile");
|
||||
check(!profile.path("limits").has("sound"),"Sound is outside this qualification");
|
||||
for(var boundary:profile.path("evidence"))try(var evidence=guideType.getClassLoader().getResourceAsStream(boundary.path("evidencePath").asText())) {
|
||||
check(evidence!=null,"Missing installed boundary evidence");check(java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(evidence.readAllBytes())).equals(boundary.path("evidenceSha256").asText()),"Installed capacity evidence changed");
|
||||
}
|
||||
}
|
||||
System.out.println("Installed shared asset authoring and capacity evidence verified");
|
||||
|
||||
check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:generic-contracts.md")), "Missing installed generic-contract specification");
|
||||
check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/contracts.pbs")), "Missing installed generic-contract example");
|
||||
check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:generic-structs-and-free-functions.md")), "Missing installed generic struct/function specification");
|
||||
@@ -78,6 +96,7 @@ public final class InstalledKnowledgeProbe {
|
||||
check(result.bytecodeModule().functions().stream().filter(f -> f.metadata().role() == role).count() == 1,
|
||||
"Installed example must preserve exactly one " + role);
|
||||
}
|
||||
verifyIsolatedTargets(root.resolve("isolated-tests"));
|
||||
Path listRoot=Files.createDirectory(Path.of("list-example")).toRealPath();
|
||||
Files.createDirectories(listRoot.resolve("src"));
|
||||
Files.copy(root.resolve("prometeu.json"),listRoot.resolve("prometeu.json"));
|
||||
@@ -143,6 +162,28 @@ public final class InstalledKnowledgeProbe {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static void verifyIsolatedTargets(Path root) throws Exception {
|
||||
var originals = new java.util.HashMap<Path, byte[]>();
|
||||
try (var files = Files.walk(root.resolve("src"))) {
|
||||
for (var file : files.filter(Files::isRegularFile).toList()) originals.put(file, Files.readAllBytes(file));
|
||||
}
|
||||
for (var target : java.util.List.of("life", "life-fail", "production")) {
|
||||
Path output = target.equals("production") ? null : root.resolve(".studio/test-builds/" + target + "/installed");
|
||||
var config = target.equals("production") ? new BuilderPipelineConfig(false, root.toString())
|
||||
: new BuilderPipelineConfig(false, root.toString(), null, null, target, output);
|
||||
var result = BuilderPipelineService.INSTANCE.compile(BuilderPipelineContext.fromConfig(config), LogAggregator.stdout());
|
||||
check(result.diagnostics().stream().noneMatch(issue -> issue.isError()),
|
||||
"Installed isolated target must compile: " + target + " " + result.diagnostics());
|
||||
check(result.bytecodeBytes().length > 0, "Installed isolated target must produce bytecode: " + target);
|
||||
boolean logs = result.bytecodeModule().syscalls().stream().anyMatch(call -> call.module().equals("log"));
|
||||
check(logs == !target.equals("production"), "Test log support must remain outside production: " + target);
|
||||
for (var original : originals.entrySet())
|
||||
check(java.util.Arrays.equals(original.getValue(), Files.readAllBytes(original.getKey())),
|
||||
"Installed target must preserve production source/barrel: " + original.getKey());
|
||||
}
|
||||
System.out.println("Installed isolated targets verified: life, life-fail and default production");
|
||||
}
|
||||
|
||||
private static void verifySpecificationAliases(ClassLoader loader,
|
||||
java.util.List<p.studio.compiler.services.FrontendReferenceProvider.Reference> docs) throws Exception {
|
||||
var resource = loader.getResource("pbs-knowledge/index.json");
|
||||
|
||||
@@ -14,6 +14,9 @@ class InstalledKnowledgeTest {
|
||||
@Test void installedJarsProvideAllReferencesAndCompileTheExampleOutsideTheCheckout() throws Exception {
|
||||
String log = runProbe();
|
||||
assertTrue(log.contains("references; example compiled"), log);
|
||||
assertTrue(log.contains("Installed shared asset authoring and capacity evidence verified"), log);
|
||||
assertTrue(log.contains("Installed lifecycle and recovery guide verified"), log);
|
||||
assertTrue(log.contains("Installed isolated targets verified: life, life-fail and default production"), log);
|
||||
assertTrue(log.contains("Packaged external sources verified"), log);
|
||||
assertTrue(log.contains("Installed specification aliases verified: 12 canonical resources"), log);
|
||||
assertTrue(log.contains("Installed List/Cursor execution fixture generated"), log);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package p.studio.app.compiler;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.ProjectCatalog;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.api.shipper.Shipper;
|
||||
import p.studio.app.StudioApplicationConfiguration;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Real compiler/packer/project composition, no guest or runtime installation required. */
|
||||
class TargetBuildIntegrationTest {
|
||||
@TempDir Path root;
|
||||
ConfigurableApplicationContext app;ProjectSession project;TaskTools tools;String task;ObjectMapper mapper;
|
||||
@BeforeEach void open()throws Exception {
|
||||
root=root.toRealPath();Files.createDirectories(root.resolve("src"));Files.createDirectories(root.resolve("tests/life"));Files.createDirectories(root.resolve("tests/shop"));
|
||||
Files.writeString(root.resolve("src/main.pbs"),"[Frame] fn frame() -> void {}\n");
|
||||
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;\n");
|
||||
Files.writeString(root.resolve("tests/life/main.pbs"),"[Frame] fn frame() -> void {}\n");
|
||||
Files.writeString(root.resolve("tests/shop/main.pbs"),"[Frame] fn frame() -> void {}\n");
|
||||
Files.writeString(root.resolve("prometeu.json"),"""
|
||||
{"name":"targetfixture","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","app_id":123,"dependencies":[],
|
||||
"testTargets":{"schemaVersion":1,"targets":[
|
||||
{"id":"life","entrypoint":"tests/life/main.pbs","sourceRoots":["src","tests/life"],"supportRoots":[],"exclusions":["src/main.pbs"],"cases":["health"],"logTag":41000},
|
||||
{"id":"shop-save","entrypoint":"tests/shop/main.pbs","sourceRoots":["src","tests/shop"],"supportRoots":[],"exclusions":["src/main.pbs"],"cases":["save"],"logTag":41001}]}}
|
||||
""");
|
||||
app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(true).run();
|
||||
mapper=app.getBean(ObjectMapper.class);project=app.getBean(ProjectSessionFactory.class).open(app.getBean(ProjectCatalog.class).openProject(root));
|
||||
tools=app.getBean(TaskTools.class);project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tools.acquire(root).task().value();
|
||||
}
|
||||
@AfterEach void close(){try{if(project!=null)project.close();}finally{if(app!=null)app.close();}}
|
||||
TrackedOperation build(String request,String target)throws Exception {
|
||||
tools.build(root,task,request,target);long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(30);
|
||||
do {var operation=tools.operation(root,task,new OperationLookup(null,request));if(operation.workerTerminated())return operation;Thread.sleep(5);}while(System.nanoTime()<deadline);
|
||||
throw new AssertionError("Target build worker did not terminate");
|
||||
}
|
||||
@Test void immutableTargetArtifactsProvenanceDedupAndManualProductionBuildAreIndependent()throws Exception {
|
||||
byte[] production=Files.readAllBytes(root.resolve("src/main.pbs"));
|
||||
var first=build("life-build","life");assertNotNull(first.buildResult());assertTrue(first.buildResult().success(),first.buildResult().diagnostics().toString());
|
||||
assertNotNull(first.buildId());Path firstRoot=root.resolve(".studio/test-builds/life").resolve(first.buildId());
|
||||
assertEquals(firstRoot.resolve("manifest.json"),first.buildResult().manifestPath());assertFalse(Files.exists(root.resolve("build/manifest.json")));
|
||||
byte[] originalPbx=Files.readAllBytes(firstRoot.resolve("program.pbx"));byte[] originalManifest=Files.readAllBytes(firstRoot.resolve("manifest.json"));
|
||||
var provenance=mapper.readTree(firstRoot.resolve("build-provenance.json").toFile());
|
||||
assertEquals("life",provenance.path("targetId").asText());assertEquals(first.buildId(),provenance.path("buildId").asText());
|
||||
assertTrue(provenance.path("sources").has(root.resolve("tests/life/main.pbs").toString()));
|
||||
assertFalse(provenance.path("sources").has(root.resolve("src/main.pbs").toString()));
|
||||
assertTrue(provenance.path("dependencyConfigurationSha256").has(root.resolve("prometeu.json").toString()));
|
||||
assertEquals(64,provenance.path("revision").asText().length());
|
||||
var duplicate=tools.build(root,task,"life-build","life");assertEquals(first.operation().id(),duplicate.operation().id());
|
||||
assertEquals(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,assertThrows(AutomationException.class,()->tools.build(root,task,"life-build","shop-save")).failure().code());
|
||||
var second=build("shop-build","shop-save");assertTrue(second.buildResult().success(),second.buildResult().diagnostics().toString());
|
||||
assertNotEquals(first.buildId(),second.buildId());
|
||||
assertArrayEquals(originalPbx,Files.readAllBytes(firstRoot.resolve("program.pbx")));assertArrayEquals(originalManifest,Files.readAllBytes(firstRoot.resolve("manifest.json")));
|
||||
assertEquals(first.buildId(),tools.operation(root,task,new OperationLookup(null,"life-build")).buildId());
|
||||
tools.release(root,task).toCompletableFuture().get(10,TimeUnit.SECONDS);
|
||||
var manual=app.getBean(Shipper.class).prepare(project.projectReference(),ignored->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);
|
||||
assertTrue(manual.success(),manual.diagnostics().toString());assertEquals(root.resolve("build/manifest.json"),manual.manifestPath());assertEquals("production",manual.context().get("targetId"));
|
||||
assertArrayEquals(production,Files.readAllBytes(root.resolve("src/main.pbs")));assertArrayEquals(originalPbx,Files.readAllBytes(firstRoot.resolve("program.pbx")));
|
||||
}
|
||||
@Test void invalidSelectedSourceCannotPublishATestCartridgeOrUsableBuildIdentity()throws Exception {
|
||||
byte[] source=Files.readAllBytes(root.resolve("src/main.pbs"));Files.writeString(root.resolve("tests/life/bad.pbs"),"fn broken( this is invalid\n");
|
||||
var result=build("bad-test","life");assertNull(result.buildId());assertNotNull(result.buildResult());assertFalse(result.buildResult().success());
|
||||
assertNull(result.buildResult().manifestPath());
|
||||
assertTrue(result.buildResult().issues().stream().anyMatch(issue->String.valueOf(issue.toMap().get("origin")).contains("tests/life/bad.pbs")),result.buildResult().issues().toString());
|
||||
try(var files=Files.walk(root.resolve(".studio/test-builds/life"))) {assertTrue(files.noneMatch(p->p.getFileName().toString().equals("manifest.json")));}
|
||||
assertArrayEquals(source,Files.readAllBytes(root.resolve("src/main.pbs")));
|
||||
var production=build("production-after-rejection",null);assertTrue(production.buildResult().success(),production.buildResult().diagnostics().toString());
|
||||
}
|
||||
@Test void cancellationWaitsForCleanupAndSourceRevisionChangesRefusePublication()throws Exception {
|
||||
var before=build("retained","shop-save");assertTrue(before.buildResult().success(),before.buildResult().diagnostics().toString());
|
||||
byte[] manifest=Files.readAllBytes(before.buildResult().manifestPath());
|
||||
var entered=new java.util.concurrent.CountDownLatch(1);var staged=new java.util.concurrent.atomic.AtomicReference<Path>();
|
||||
var paused=shipperAfterCompile((project,output)->{
|
||||
staged.set(output);entered.countDown();
|
||||
try {new java.util.concurrent.CountDownLatch(1).await();}
|
||||
catch(InterruptedException interrupted){Thread.currentThread().interrupt();throw new java.util.concurrent.CancellationException("Cancelled fixture after compile");}
|
||||
});
|
||||
var candidate=new BuildSelection("life",UUID.randomUUID().toString());
|
||||
var operation=project.automation().submit(project.automation().snapshot().task(),"Test build cancellation",()->{
|
||||
paused.prepareNow(project.projectReference(),candidate,ignored->{});
|
||||
return new AutomationOutcome(AutomationOutcome.Kind.CANCELLED,0,0,List.of(),null);
|
||||
});
|
||||
assertTrue(entered.await(10,TimeUnit.SECONDS));assertTrue(Files.isRegularFile(staged.get().resolve("program.pbx")));
|
||||
operation.cancel();operation.termination().toCompletableFuture().get(10,TimeUnit.SECONDS);
|
||||
assertFalse(Files.exists(staged.get()));assertFalse(Files.exists(root.resolve(".studio/test-builds/life").resolve(candidate.buildId())));
|
||||
assertArrayEquals(manifest,Files.readAllBytes(before.buildResult().manifestPath()));
|
||||
var changed=shipperAfterCompile((project,output)->{
|
||||
try {Files.writeString(root.resolve("tests/life/main.pbs"),"[Frame] fn frame() -> void { let external: int = 1; }\n");}
|
||||
catch(java.io.IOException failure){throw new java.io.UncheckedIOException(failure);}
|
||||
});
|
||||
var changedSelection=new BuildSelection("life",UUID.randomUUID().toString());
|
||||
var result=new java.util.concurrent.atomic.AtomicReference<p.studio.api.shipper.ShipperPrepareResult>();
|
||||
var changeOperation=project.automation().submit(project.automation().snapshot().task(),"Changed source build",()->{
|
||||
result.set(changed.prepareNow(project.projectReference(),changedSelection,ignored->{}));
|
||||
return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED,0,0,List.of(),null);
|
||||
});
|
||||
changeOperation.completion().toCompletableFuture().get(10,TimeUnit.SECONDS);changeOperation.termination().toCompletableFuture().get(10,TimeUnit.SECONDS);
|
||||
assertFalse(result.get().success());assertTrue(result.get().diagnostics().stream().anyMatch(m->m.contains("Consumed source changed")),result.get().diagnostics().toString());
|
||||
assertFalse(Files.exists(root.resolve(".studio/test-builds/life").resolve(changedSelection.buildId())));
|
||||
assertArrayEquals(manifest,Files.readAllBytes(before.buildResult().manifestPath()));
|
||||
}
|
||||
@Test void packagedLifeExamplesCompileBothTargetsWithLogSupportAbsentFromProduction()throws Exception {
|
||||
project.close();Path copy=root.resolve("packaged-example");Files.createDirectories(copy);
|
||||
String prefix="pbs:example:game:1:isolated-tests/";int files=0;
|
||||
for(var reference:p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1,p.studio.AppMode.Game)) {
|
||||
if(!reference.id().startsWith(prefix))continue;
|
||||
Path destination=copy.resolve(reference.id().substring(prefix.length()));Files.createDirectories(destination.getParent());Files.writeString(destination,reference.text());files++;
|
||||
}
|
||||
assertTrue(files>=10,"Packaged isolated test example is missing");root=copy.toRealPath();
|
||||
project=app.getBean(ProjectSessionFactory.class).open(app.getBean(ProjectCatalog.class).openProject(root));
|
||||
project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tools.acquire(root).task().value();
|
||||
byte[] barrel=Files.readAllBytes(root.resolve("src/mod.barrel"));
|
||||
for(String target:List.of("life","life-fail","production")) {
|
||||
var result=build("packaged-"+target,target);assertTrue(result.buildResult().success(),result.buildResult().diagnostics().toString());
|
||||
var manifest=mapper.readTree(result.buildResult().manifestPath().toFile());
|
||||
boolean usesLog=java.util.stream.StreamSupport.stream(manifest.path("capabilities").spliterator(),false).anyMatch(v->v.asText().equals("log"));
|
||||
assertEquals(!target.equals("production"),usesLog);
|
||||
assertArrayEquals(barrel,Files.readAllBytes(root.resolve("src/mod.barrel")));
|
||||
}
|
||||
}
|
||||
p.studio.core.shipper.StudioShipperService shipperAfterCompile(java.util.function.BiConsumer<p.studio.api.project.ProjectReference,Path> after) {
|
||||
var actual=app.getBean(p.studio.core.shipper.CompilerBuildGateway.class);
|
||||
var wrapped=new p.studio.core.shipper.CompilerBuildGateway() {
|
||||
public CompilerBuildOutput compile(p.studio.api.project.ProjectReference project,java.util.function.Consumer<String> sink){return actual.compile(project,sink);}
|
||||
public CompilerBuildOutput compile(p.studio.api.project.ProjectReference project,BuildSelection selection,Path output,java.util.function.Consumer<String> sink){
|
||||
var result=actual.compile(project,selection,output,sink);after.accept(project,output);return result;
|
||||
}
|
||||
};
|
||||
return new p.studio.core.shipper.StudioShipperService(wrapped,app.getBean(p.packer.PackerWorkspaceService.class),mapper,app.getBean(p.studio.api.operation.OperationExecutor.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package p.studio.app.evidence;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.operation.*;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.app.mcp.*;
|
||||
import p.studio.core.project.ProjectAccessRegistry;
|
||||
import p.studio.core.session.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class EvidenceIntegrationTest {
|
||||
@TempDir Path root;
|
||||
ExecutorService pool;DefaultAutomationSession session;ProjectAccessRegistry projects;ObjectMapper mapper=new ObjectMapper();
|
||||
PngEvidenceCodec codec=new PngEvidenceCodec();EvidenceTools tools;String task;byte[] png;AtomicInteger lookups;
|
||||
@BeforeEach void open()throws Exception {
|
||||
root=root.toRealPath();pool=Executors.newCachedThreadPool();projects=new ProjectAccessRegistry();
|
||||
session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(pool));projects.register(root,session::enterManual,()->true,session);
|
||||
png=codec.encode(new Evidence.Pixels(2,1,new byte[]{10,20,30,0,40,50,60,(byte)255}));lookups=new AtomicInteger();
|
||||
TaskTools original=(TaskTools)java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{TaskTools.class},(proxy,method,args)->{
|
||||
if(!method.getName().equals("operation"))throw new AssertionError("Evidence must never invoke "+method.getName());
|
||||
lookups.incrementAndGet();var capture=new CanonicalCapture("native-session","build",5,9,2,1,2,png);
|
||||
return new TrackedOperation(new OperationSnapshot(new OperationId("original-operation"),OperationState.SUCCEEDED,Instant.now(),"advance"),"advance-request",new TrackedOperation.Progress(1L,1L),null,null,
|
||||
new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED,1,1,List.of(),capture),null,true,true);
|
||||
});
|
||||
tools=new DefaultEvidenceTools(projects,original,new FileEvidenceStore(mapper),codec);
|
||||
session.grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=session.acquire().task().value();
|
||||
}
|
||||
@AfterEach void close(){if(session!=null)session.closeAsync().toCompletableFuture().join();if(pool!=null)pool.shutdownNow();}
|
||||
Evidence.Publication persist(){return tools.persist(root,task,"persist",new OperationLookup("original-operation",null));}
|
||||
@Test void originalCheckpointDedupReopenAndReacquisitionDoNotCallRuntimeOrRewriteHistory()throws Exception {
|
||||
var p=persist();var a=p.artifacts().getFirst();assertArrayEquals(png,tools.image(root,task,a.id()));
|
||||
assertEquals("original-operation",a.provenance().get("operationId"));assertEquals(9,((Number)a.provenance().get("frameId")).intValue());
|
||||
assertEquals(p,tools.persist(root,task,"persist",new OperationLookup("original-operation",null)));assertEquals(1,lookups.get());
|
||||
assertEquals(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,assertThrows(AutomationException.class,()->tools.persist(root,task,"persist",new OperationLookup("other",null))).failure().code());
|
||||
String oldTask=task;session.release(session.snapshot().task()).toCompletableFuture().get(5,TimeUnit.SECONDS);
|
||||
assertThrows(ControlDeniedException.class,()->tools.metadata(root,oldTask,a.id()));
|
||||
// Human inspection survives authority return; persisted history is independent of the live operation cache.
|
||||
assertTrue(tools.metadata(root,null,a.id()).stale());
|
||||
session.closeAsync().toCompletableFuture().join();
|
||||
projects=new ProjectAccessRegistry();session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(pool));projects.register(root,session::enterManual,()->true,session);
|
||||
tools=new DefaultEvidenceTools(projects,null,new FileEvidenceStore(mapper),codec);
|
||||
session.grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=session.acquire().task().value();
|
||||
assertArrayEquals(png,tools.image(root,task,a.id()));assertEquals(p.id(),tools.list(root,task).getFirst().id());assertTrue(tools.metadata(root,task,a.id()).stale());
|
||||
assertEquals(p.id(),tools.persist(root,task,"persist",new OperationLookup("original-operation",null)).id());assertEquals(1,lookups.get());
|
||||
}
|
||||
@Test void referenceAdmissionCanonicalPathsQuotaBoundsAndIntegrity()throws Exception {
|
||||
Path external=Files.createTempFile("studio-reference-",".png");
|
||||
try {
|
||||
Files.write(external,png);Path link=root.resolve("escape.png");Files.createSymbolicLink(link,external);
|
||||
assertEquals(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE,assertThrows(AutomationException.class,()->tools.importReference(root,task,"escape",link,null)).failure().code());
|
||||
assertThrows(ControlDeniedException.class,()->tools.authorizeReference(root,external));
|
||||
session.release(session.snapshot().task()).toCompletableFuture().join();String grant=tools.authorizeReference(root,external);
|
||||
var imported=tools.importReference(root,null,"selected",external,grant);assertNull(imported.baseline());assertEquals("external",imported.artifacts().getFirst().provenance().get("origin"));
|
||||
var a=imported.artifacts().getFirst();assertNull(a.provenance().get("frameId"));
|
||||
assertArrayEquals(Arrays.copyOfRange(png,1,4),tools.read(root,null,a.id(),1,3).bytes());
|
||||
assertThrows(IllegalArgumentException.class,()->tools.read(root,null,a.id(),png.length,1));
|
||||
assertThrows(IllegalArgumentException.class,()->tools.read(root,null,a.id(),0,Evidence.MAX_READ+1));
|
||||
var low=new FileEvidenceStore(mapper,1);var refusal=assertThrows(AutomationException.class,()->low.publish(root,new Evidence.Publication(UUID.randomUUID().toString(),"overflow","key",root.toString(),Instant.now().toString(),List.of(),null,null),List.of()));
|
||||
assertEquals(AutomationFailure.Code.LIMIT_EXCEEDED,refusal.failure().code());assertTrue(refusal.failure().details().containsKey("used"));
|
||||
assertArrayEquals(png,tools.image(root,null,a.id()));
|
||||
Files.write(root.resolve(".studio/evidence/pub-"+imported.id()).resolve(a.id()+".png"),new byte[]{1});
|
||||
assertThrows(AutomationException.class,()->tools.image(root,null,a.id()));
|
||||
}finally{Files.deleteIfExists(external);}
|
||||
}
|
||||
@Test void comparisonMcpImageMetricsAndHumanOnlyBaselineReviewShareOneResult()throws Exception {
|
||||
var actual=persist().artifacts().getFirst();Path reference=root.resolve("reference.png");Files.write(reference,png);
|
||||
var expected=tools.importReference(root,task,"reference",reference,null).artifacts().getFirst();
|
||||
assertEquals(false,expected.provenance().get("humanSelected"));
|
||||
assertEquals(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,assertThrows(AutomationException.class,
|
||||
()->tools.importReference(root,task,"reference",reference,"unverified-grant")).failure().code());
|
||||
var report=tools.compare(root,task,"comparison",expected.id(),actual.id(),Evidence.Parameters.exact(Evidence.Alpha.compare));
|
||||
assertEquals(Evidence.Verdict.passed,report.report().verdict());assertEquals(2,report.report().comparedPixels());assertEquals(1,lookups.get());
|
||||
assertThrows(ControlDeniedException.class,()->tools.approveBaseline(root,expected.id(),null));
|
||||
var registry=new McpToolRegistry(new McpToolCatalog(mapper),mapper,McpEvidenceTools.handlers(tools,mapper));
|
||||
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("artifactId",actual.id());
|
||||
var image=registry.call("studio_evidence_image",args).wire();assertArrayEquals(png,Base64.getDecoder().decode(image.path("content").get(1).path("data").asText()));
|
||||
assertEquals(actual.sha256(),image.path("structuredContent").path("value").path("artifact").path("sha256").asText());
|
||||
assertEquals(AutomationFailure.Code.BUSY,assertThrows(AutomationException.class,()->tools.delete(root,task,actual.publicationId())).failure().code());
|
||||
session.release(session.snapshot().task()).toCompletableFuture().get(5,TimeUnit.SECONDS);
|
||||
var revision=tools.approveBaseline(root,expected.id(),null);assertEquals(expected.id(),revision.baseline().artifactId());
|
||||
assertThrows(AutomationException.class,()->tools.approveBaseline(root,actual.id(),null));
|
||||
var revision2=tools.approveBaseline(root,expected.id(),revision.baseline().id());assertEquals(revision.baseline().id(),revision2.baseline().previousRevision());
|
||||
assertThrows(AutomationException.class,()->tools.delete(root,null,expected.publicationId()));
|
||||
assertTrue(tools.list(root,null).stream().anyMatch(p->p.id().equals(report.id())));
|
||||
assertEquals("INVALID_TASK",registry.call("studio_evidence_image",args).wire().path("structuredContent").path("error").path("code").asText());
|
||||
}
|
||||
@Test void interruptedAndAbandonedStagingNeverPublishesOrChangesBaseline()throws Exception {
|
||||
var p=persist();Path stage=root.resolve(".studio/evidence/staging-interrupted");Files.createDirectories(stage);Files.write(stage.resolve("partial.png"),new byte[]{1,2});
|
||||
var reopened=new FileEvidenceStore(mapper);assertEquals(1,reopened.list(root).size());assertFalse(Files.exists(stage));
|
||||
Thread.currentThread().interrupt();
|
||||
try {
|
||||
var next=new Evidence.Publication(UUID.randomUUID().toString(),"cancelled","cancelled",root.toString(),Instant.now().toString(),List.of(),null,null);
|
||||
assertThrows(AutomationException.class,()->reopened.publish(root,next,List.of()));
|
||||
}finally{Thread.interrupted();}
|
||||
assertEquals(1,reopened.list(root).size());assertArrayEquals(png,reopened.image(root,p.artifacts().getFirst().id()));
|
||||
}
|
||||
@Test void concurrentPublishersCannotBypassExactQuotaAndOtherProjectCannotReuseAnExternalGrant()throws Exception {
|
||||
var p1=new Evidence.Publication(UUID.randomUUID().toString(),"one","one",root.toString(),"2026-11-10T00:00:00Z",List.of(),null,null);
|
||||
var p2=new Evidence.Publication(UUID.randomUUID().toString(),"two","two",root.toString(),"2026-11-10T00:00:00Z",List.of(),null,null);
|
||||
long size=mapper.writeValueAsBytes(p1).length;assertEquals(size,mapper.writeValueAsBytes(p2).length);
|
||||
var store=new FileEvidenceStore(mapper,size);var start=new CountDownLatch(1);
|
||||
var first=pool.submit(()->{start.await();try{store.publish(root,p1,List.of());return "ok";}catch(AutomationException e){return e.failure().code().name();}});
|
||||
var second=pool.submit(()->{start.await();try{store.publish(root,p2,List.of());return "ok";}catch(AutomationException e){return e.failure().code().name();}});
|
||||
start.countDown();assertEquals(Set.of("ok","LIMIT_EXCEEDED"),Set.of(first.get(5,TimeUnit.SECONDS),second.get(5,TimeUnit.SECONDS)));assertEquals(1,store.list(root).size());
|
||||
Path other=Files.createDirectory(root.resolve("other-project"));Path external=Files.createTempFile("outside-reference-",".png");
|
||||
try {
|
||||
Files.write(external,png);String grant=store.authorizeReference(root,external);
|
||||
assertThrows(AutomationException.class,()->store.importReference(other,external,grant));
|
||||
// A valid artifact identifier does not escape the other project's namespace.
|
||||
var saved=persist();assertThrows(AutomationException.class,()->store.image(other,saved.artifacts().getFirst().id()));
|
||||
}finally{Files.deleteIfExists(external);}
|
||||
}
|
||||
}
|
||||
@@ -198,4 +198,28 @@ class LocalMcpServerTest {
|
||||
assertEquals(401, post(wire).statusCode());
|
||||
}
|
||||
|
||||
@Test void evidenceImagesUseAuthenticatedEndpointAndCannotReuseRevokedTasksOrCrossProjectIds() throws Exception {
|
||||
root=root.toRealPath();var pool=java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
var authority=new p.studio.core.session.DefaultAutomationSession(root,new p.studio.app.operation.ExecutorOperationExecutor(pool));
|
||||
var projects=new p.studio.core.project.ProjectAccessRegistry();projects.register(root,authority::enterManual,()->!authority.snapshot().closed(),authority);
|
||||
var codec=new p.studio.app.evidence.PngEvidenceCodec();var tools=new p.studio.core.session.DefaultEvidenceTools(projects,null,new p.studio.app.evidence.FileEvidenceStore(mapper),codec);
|
||||
byte[] png=codec.encode(new Evidence.Pixels(1,1,new byte[]{1,2,3,(byte)255}));
|
||||
var source=root.resolve("reference.png");java.nio.file.Files.write(source,png);
|
||||
var artifact=tools.importReference(root,null,"human-import",source,null).artifacts().getFirst();
|
||||
try {
|
||||
server.close();server=new LocalMcpServer(mapper,new McpToolRegistry(new McpToolCatalog(mapper),mapper,McpEvidenceTools.handlers(tools,mapper)));
|
||||
server.start();authorize(root);session=null;initialize();
|
||||
authority.grant(false).toCompletableFuture().get(5,java.util.concurrent.TimeUnit.SECONDS);String task=authority.acquire().task().value();
|
||||
var call=mapper.createObjectNode().put("jsonrpc","2.0").put("id",2).put("method","tools/call");
|
||||
var args=call.putObject("params").put("name","studio_evidence_image").putObject("arguments").put("projectRoot",root.toString()).put("taskId",task).put("artifactId",artifact.id());
|
||||
assertEquals(401,request("POST",server.connection().endpoint(),call.toString(),null,null,LocalMcpServer.PROTOCOL_VERSION,session).statusCode());
|
||||
var result=mapper.readTree(post(call.toString()).body()).path("result");assertFalse(result.path("isError").asBoolean());
|
||||
assertArrayEquals(png,Base64.getDecoder().decode(result.path("content").get(1).path("data").asText()));
|
||||
args.put("projectRoot",java.nio.file.Files.createDirectory(root.resolve("other")).toRealPath().toString());
|
||||
assertEquals("OUTSIDE_PROJECT_SCOPE",mapper.readTree(post(call.toString()).body()).path("result").path("structuredContent").path("error").path("code").asText());
|
||||
args.put("projectRoot",root.toString());authority.release(authority.snapshot().task()).toCompletableFuture().get(5,java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertEquals("INVALID_TASK",mapper.readTree(post(call.toString()).body()).path("result").path("structuredContent").path("error").path("code").asText());
|
||||
} finally {authority.closeAsync().toCompletableFuture().join();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ class McpContractTest {
|
||||
final McpToolCatalog catalog = new McpToolCatalog(mapper);
|
||||
|
||||
@Test void everyToolHasValidExampleAuthorityAndResultEnvelope() {
|
||||
assertEquals(24, catalog.names().size());
|
||||
assertEquals(48, catalog.names().size());
|
||||
for (var name : catalog.names()) {
|
||||
var definition = catalog.definition(name);
|
||||
assertDoesNotThrow(() -> catalog.validateArguments(name, definition.get("exampleArguments")), name + " arguments");
|
||||
|
||||
@@ -127,6 +127,8 @@ class McpTaskToolsTest {
|
||||
assertEquals(true, runtime.input.get("a")); assertEquals(false, runtime.input.get("up")); assertEquals(0, runtime.input.get("touchY"));
|
||||
var receipt = value(call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 5)));
|
||||
var result = completed("advance"); assertEquals(1, runtime.advances.get());
|
||||
assertEquals("advance", result.path("observation").path("context").path("clientRequestId").asText());
|
||||
assertTrue(result.has("currentObservation"));
|
||||
assertEquals(5, result.path("progress").path("completedFrames").asInt());
|
||||
assertEquals(receipt.path("operationId"), value(call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 5))).path("operationId"));
|
||||
error("CLIENT_REQUEST_CONFLICT", call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 6)));
|
||||
@@ -138,6 +140,7 @@ class McpTaskToolsTest {
|
||||
value(call("studio_headless_capture", args()));
|
||||
for (var operation : List.of("state", "fault", "clear_input", "reset")) value(call("studio_headless_" + operation, args()));
|
||||
assertTrue(session.snapshot().stale());
|
||||
assertEquals(result.path("observation"), poll("advance").path("observation"));
|
||||
assertTrue(poll("advance").path("capture").path("stale").asBoolean());
|
||||
value(call("studio_headless_shutdown", args())); assertTrue(runtime.stopped);
|
||||
error("SESSION_NOT_FOUND", call("studio_headless_state", args()));
|
||||
|
||||
@@ -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(24, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
|
||||
assertEquals(48, 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")));
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.app.assets.SmallAssetProject;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Provider qualification precedes publication of a consumer capacity profile. No managed-guard bypass in production. */
|
||||
class AssetCapacityInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
@Test void actualInstalledPoolsAcceptSixteenAndRejectSeventeenGlyphAndScenePreloads()throws Exception {
|
||||
Path installation=Path.of(System.getProperty("studio.test.runtimeInstall","")).toRealPath();
|
||||
assertTrue(Files.isExecutable(installation.resolve("prometeu-headless")));
|
||||
var json=new com.fasterxml.jackson.databind.ObjectMapper();var observations=new ArrayList<Map<String,Object>>();
|
||||
for(String type:List.of("glyph","scene"))for(int count:List.of(16,17)) {
|
||||
try(var fixture=new SmallAssetProject(root.resolve(type+count))) {
|
||||
var source=type.equals("scene")?fixture.glyph("source",false):null;
|
||||
for(int i=0;i<count;i++)if(type.equals("glyph"))fixture.glyph("bank"+i,true);else fixture.scene("bank"+i,source,true);
|
||||
var build=fixture.build();assertTrue(build.success(),build.diagnostics().toString());
|
||||
var plan=fixture.packer.workspaceService().planPackWorkspace(new p.packer.messages.PackerProjectContext(fixture.project.name(),fixture.root));
|
||||
assertEquals(count,plan.preload().stream().filter(p->p.bankType().equals(type.toUpperCase(Locale.ROOT))).count());
|
||||
var process=new ProcessBuilder(installation.resolve("prometeu").toString(),"headless","--stdio").directory(fixture.root.toFile()).start();
|
||||
var session=new HeadlessProcessSession(process,json,HeadlessLimits.defaults(),"qualify-"+type+count);
|
||||
var record=new LinkedHashMap<String,Object>();record.put("bankType",type);record.put("preloads",count);record.put("plan",plan);
|
||||
try {
|
||||
session.initializeAndBoot(build.manifestPath().getParent(),fixture.root,false,Map.of());
|
||||
var result=session.advance(1,progress->{});record.put("observation",result.observation());record.put("outcome",result.kind().name());
|
||||
if(count==16){assertEquals(AutomationOutcome.Kind.SUCCEEDED,result.kind(),result.toString());assertEquals(1,result.completedFrames());}
|
||||
else assertNotEquals(AutomationOutcome.Kind.SUCCEEDED,result.kind(),"Seventeenth preload must be rejected by the native pool");
|
||||
}catch(AutomationException failure) {
|
||||
record.put("failure",failure.failure());assertEquals(17,count,"Sixteen native preloads must boot and execute");
|
||||
var nativeFacts=json.valueToTree(failure.failure().runtimeError());
|
||||
assertEquals("boot_failed",nativeFacts.path("code").asText(),nativeFacts.toString());
|
||||
assertEquals("vm_panic",nativeFacts.path("details").path("fault").path("kind").asText(),nativeFacts.toString());
|
||||
assertEquals("Cartridge preload failed: BackendError",nativeFacts.path("details").path("fault").path("message").asText(),nativeFacts.toString());
|
||||
}finally {
|
||||
record.put("nativeObservation",session.observation());
|
||||
try{session.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}finally{if(session.alive())session.abort("Capacity qualification cleanup");}
|
||||
}
|
||||
record.put("expected",count==16?"accepted":"rejected");observations.add(record);
|
||||
}
|
||||
}
|
||||
Path output=Path.of("build/asset-authoring-qualification");Files.createDirectories(output);
|
||||
var executables=new TreeMap<String,String>();for(String file:List.of("prometeu","prometeu-headless","prometeu-runtime"))executables.put(file,HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(installation.resolve(file)))));
|
||||
var nativeObservation=(RuntimeObservation)observations.getFirst().get("nativeObservation");
|
||||
json.writerWithDefaultPrettyPrinter().writeValue(output.resolve("native-capacity-boundaries.json").toFile(),Map.of("installation",installation.toString(),"runtimeVersion",nativeObservation.nativeDetails().get("runtimeVersion"),"executables",executables,"observations",observations,"scope","Actual packaged native 16/17 qualification, glyph/scene only; no runtime writes/builds or larger guest budgets. Native rejection reports the existing aggregate preload BackendError, not a fabricated slot detail."));
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBudgets.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.app.assets.*;
|
||||
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
|
||||
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.*;
|
||||
|
||||
/** Real qualified build/preflight and process execution, independent of the provider boundary qualification. */
|
||||
class AssetManagedBuildInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
Map<String,String> files(Path directory)throws Exception {
|
||||
var result=new TreeMap<String,String>();try(var paths=Files.walk(directory)){for(Path file:paths.filter(Files::isRegularFile).toList())result.put(directory.relativize(file).toString(),HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file))));}return result;
|
||||
}
|
||||
@Test void bothPoolsRejectSeventeenthBeforePublicationThenReducedPreloadBuildRunsWithSameGuard()throws Exception {
|
||||
String install=System.getProperty("studio.test.runtimeInstall","");assertFalse(install.isBlank());var setup=new ProjectLocalStudioSetup(install,null);
|
||||
var evidence=new ArrayList<Map<String,Object>>();
|
||||
for(String type:List.of("glyph","scene"))try(var fixture=new SmallAssetProject(root.resolve(type));var workers=Executors.newFixedThreadPool(2)) {
|
||||
var source=type.equals("scene")?fixture.glyph("source",false):null;
|
||||
for(int i=0;i<16;i++)if(type.equals("glyph"))fixture.glyph("bank"+i,true);else fixture.scene("bank"+i,source,true);
|
||||
var budgets=new AssetBudgetInspection(fixture.json,fixture.packer.workspaceService(),p->setup);
|
||||
var snapshot=budgets.inspect(fixture.project);assertEquals(QualificationState.known,snapshot.qualification().state(),snapshot.qualification().reason());assertTrue(snapshot.managedExecutionAllowed(),snapshot.toString());
|
||||
var shipper=new StudioShipperService(new CompilerBuildGatewayAdapter(),fixture.packer.workspaceService(),fixture.json,new ExecutorOperationExecutor(workers)).withAssetPreflight(budgets);
|
||||
var first=shipper.prepare(fixture.project,event->{}).completion().toCompletableFuture().get(45,TimeUnit.SECONDS);assertTrue(first.success(),first.diagnostics().toString());
|
||||
var before=files(fixture.root.resolve("build"));var extra=type.equals("glyph")?fixture.glyph("extra",true):fixture.scene("extra",source,true);
|
||||
var rejected=shipper.prepare(fixture.project,event->{}).completion().toCompletableFuture().get(45,TimeUnit.SECONDS);
|
||||
assertFalse(rejected.success());assertTrue(rejected.issues().stream().anyMatch(i->"PRELOAD_CAPACITY_EXCEEDED".equals(i.toMap().get("code"))),rejected.issues().toString());assertEquals(before,files(fixture.root.resolve("build")));
|
||||
var packed=new p.studio.core.assets.PackerAssetPacking(fixture.packer.workspaceService(),new ExecutorOperationExecutor(workers)).withAssetPreflight(budgets).pack(fixture.project).completion().toCompletableFuture().get(15,TimeUnit.SECONDS);
|
||||
assertEquals(p.studio.api.assets.AssetOperationStatus.FAILED,packed.status());assertTrue(packed.diagnostics().stream().anyMatch(d->"PRELOAD_CAPACITY_EXCEEDED".equals(d.code())));assertEquals(before,files(fixture.root.resolve("build")));
|
||||
var disabled=fixture.commands.updateContract(fixture.project,extra,false,"NONE",Map.of(),type.equals("glyph")?Map.of("tile_size","16x16"):Map.of());assertTrue(disabled.success(),disabled.errorMessage());
|
||||
var reduced=budgets.inspect(fixture.project);assertTrue(reduced.buildAllowed());assertTrue(reduced.pools().stream().anyMatch(Pool::potentialExceedsKnownLimit));
|
||||
var built=shipper.prepare(fixture.project,event->{}).completion().toCompletableFuture().get(45,TimeUnit.SECONDS);assertTrue(built.success(),built.diagnostics().toString());
|
||||
var admitted=new ManagedAssetGuard(fixture.json).require(fixture.root,built.manifestPath().getParent(),setup);
|
||||
var session=new HeadlessProcessGateway(fixture.json,p->setup).boot(fixture.project,"qualified-"+type,built);
|
||||
try{var frame=session.advance(1,p->{});assertEquals(AutomationOutcome.Kind.SUCCEEDED,frame.kind());assertEquals(1,frame.completedFrames());}
|
||||
finally{session.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}
|
||||
Path program=built.manifestPath().getParent().resolve("program.pbx");byte[] originalProgram=Files.readAllBytes(program);Files.writeString(program,"changed",StandardOpenOption.APPEND);
|
||||
assertEquals("ASSET_BUILD_BYTES_CHANGED",assertThrows(AutomationException.class,()->new ManagedAssetGuard(fixture.json).require(fixture.root,built.manifestPath().getParent(),setup)).failure().details().get("code"));Files.write(program,originalProgram);
|
||||
Files.writeString(fixture.root.resolve("assets/bank0/asset.json"),"\n",StandardOpenOption.APPEND);
|
||||
assertEquals("ASSET_BUILD_INPUTS_CHANGED",assertThrows(AutomationException.class,()->new ManagedAssetGuard(fixture.json).require(fixture.root,built.manifestPath().getParent(),setup)).failure().details().get("code"));
|
||||
evidence.add(Map.of("bankType",type,"initialBudget",snapshot,"rejectedBuild",rejected.diagnosticView(),"previousOutputPreserved",true,"reducedBudget",reduced,"admission",admitted));
|
||||
}
|
||||
Path output=Path.of("build/asset-authoring-qualification");Files.createDirectories(output);
|
||||
new com.fasterxml.jackson.databind.ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(output.resolve("managed-boundaries.json").toFile(),evidence);
|
||||
}
|
||||
@Test void unqualifiedBuildAndChangedRuntimeComponentCannotStartManagedExecution()throws Exception {
|
||||
Path install=Path.of(System.getProperty("studio.test.runtimeInstall","")).toRealPath();var setup=new ProjectLocalStudioSetup(install.toString(),null);
|
||||
try(var fixture=new SmallAssetProject(root.resolve("unknown"))) {
|
||||
fixture.glyph("bank",true);var unqualified=fixture.build();assertTrue(unqualified.success());
|
||||
var failure=assertThrows(AutomationException.class,()->new ManagedAssetGuard(fixture.json).require(fixture.root,unqualified.manifestPath().getParent(),setup));
|
||||
assertEquals(AutomationFailure.Code.RUNTIME_INCOMPATIBLE,failure.failure().code());
|
||||
Path changed=Files.createDirectories(root.resolve("changed-installation"));
|
||||
for(String name:List.of("prometeu","prometeu-headless","prometeu-runtime"))Files.copy(install.resolve(name),changed.resolve(name));
|
||||
Files.writeString(changed.resolve("prometeu-headless"),"changed",StandardOpenOption.APPEND);
|
||||
var selected=new AssetCapacityProfiles(fixture.json).select(new ProjectLocalStudioSetup(changed.toString(),null));assertEquals(QualificationState.unknown,selected.state());assertTrue(selected.reason().contains("component changed"));
|
||||
assertEquals(QualificationState.unknown,new AssetCapacityProfiles(fixture.json).select(ProjectLocalStudioSetup.defaults()).state());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,10 @@ final class DirectHeadlessOracle implements AutoCloseable {
|
||||
assertEquals(1, hello.path("protocolVersion").path("major").asInt());
|
||||
var initialize = mapper.createObjectNode();
|
||||
initialize.putObject("protocolVersion").put("major", 1).put("minor", 0);
|
||||
initialize.set("requiredCapabilities", hello.path("capabilities"));
|
||||
// This independent client uses the base protocol only; advertised optional
|
||||
// capabilities can require a newer minor and must not be requested blindly.
|
||||
initialize.set("requiredCapabilities", mapper.valueToTree(List.of("boot", "reset", "set_input", "clear_input",
|
||||
"advance", "capture", "get_state", "get_fault", "cancel", "shutdown")));
|
||||
call("initialize", initialize);
|
||||
call("boot", mapper.createObjectNode().put("path", cartridge.toString()));
|
||||
} catch (Throwable failure) { terminate(); throw failure; }
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.automation.GuestTests;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GuestEventDecoderTest {
|
||||
final GuestEventDecoder decoder=new GuestEventDecoder(new ObjectMapper());
|
||||
final String valid="""
|
||||
{"schemaVersion":1,"suiteId":"life","eventId":"assert-1","kind":"assertion","caseId":"health","payload":{"name":"damage","message":"public health","expected":10,"actual":9,"passed":false}}
|
||||
""";
|
||||
@Test void versionedEventsRetainTypedAssertionPayloadAndRejectAmbiguousEnvelopes() {
|
||||
var event=decoder.decode(valid);assertEquals(GuestTests.EventKind.assertion,event.kind());assertEquals(false,event.payload().get("passed"));assertEquals(9,event.payload().get("actual"));
|
||||
for(var invalid:java.util.List.of("plain game text",valid+" {}",valid.replace("\"schemaVersion\":1","\"schemaVersion\":\"1\""),valid.replace("\"schemaVersion\":1","\"schemaVersion\":2"),valid.replace("\"passed\":false","\"passed\":true,\"passed\":false"),valid.replace("\"suiteId\":\"life\"","\"suiteId\":3"),valid.replace("\"kind\":\"assertion\"","\"kind\":\"unknown\"")))
|
||||
assertThrows(IllegalArgumentException.class,()->decoder.decode(invalid),invalid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.automation.*;
|
||||
import java.math.BigInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GuestLogWireTest {
|
||||
final ObjectMapper mapper=new ObjectMapper();
|
||||
@Test void nativeUint64ValuesAndHistoricalOverflowRemainLossless()throws Exception {
|
||||
var json=mapper.readTree("""
|
||||
{"sessionId":"session","logEpoch":0,"events":[{"sequence":0,"frame":18446744073709551615,
|
||||
"timestampMs":18446744073709551615,"level":"info","source":"app","appId":4294967295,"tag":65535,"message":"é"}],
|
||||
"oldestSequence":0,"newestSequence":0,"nextAfterSequence":0,"gap":false,"overflow":true}
|
||||
""");
|
||||
var page=HeadlessWire.logs(json,"session",null,1);
|
||||
assertEquals(new BigInteger("18446744073709551615"),page.events().getFirst().frame());assertTrue(page.overflow());assertFalse(page.gap());
|
||||
assertEquals(4294967295L,page.events().getFirst().appId());
|
||||
assertThrows(AutomationException.class,()->HeadlessWire.logs(json,"other",null,1));
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode)json).put("nextAfterSequence",1);
|
||||
assertThrows(AutomationException.class,()->HeadlessWire.logs(json,"session",null,1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.app.StudioApplicationConfiguration;
|
||||
import p.studio.core.project.ProjectLocalStudioSetupStore;
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Required pilot on a disposable copy of the actual game, using only its existing public APIs. */
|
||||
class GuestTestPilotTest {
|
||||
@TempDir Path root;
|
||||
static Map<String,String> sources(Path root)throws Exception {
|
||||
var hashes=new TreeMap<String,String>();try(var paths=Files.walk(root.resolve("src"))) {
|
||||
for(var p:paths.filter(Files::isRegularFile).toList())hashes.put(root.relativize(p).toString(),HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(p))));
|
||||
}return hashes;
|
||||
}
|
||||
@Test void publicShopCommitAndSeparateProcessReadbackPreserveOriginalSourcesAndPersonalMedia()throws Exception {
|
||||
String selected=System.getProperty("studio.test.guestPilotProject","");assertFalse(selected.isBlank(),"Supply -PstudioGuestPilotProject=<actual Zelda project>");
|
||||
Path original=Path.of(selected).toRealPath();var before=sources(original);root=root.toRealPath();
|
||||
for(String folder:List.of("src","assets"))try(var paths=Files.walk(original.resolve(folder))) {
|
||||
for(var source:paths.toList()){Path dest=root.resolve(original.relativize(source));if(Files.isDirectory(source))Files.createDirectories(dest);else Files.copy(source,dest);}
|
||||
}
|
||||
var mapper=new ObjectMapper();var manifest=(ObjectNode)mapper.readTree(original.resolve("prometeu.json").toFile());
|
||||
assertNotNull(manifest.get("memcard_slots"));var targets=manifest.putObject("testTargets").put("schemaVersion",1).putArray("targets");
|
||||
for(var name:List.of("writer","reader")) {
|
||||
Path entry=root.resolve("tests/"+name+"/main.pbs");Files.createDirectories(entry.getParent());
|
||||
try(var stream=getClass().getResourceAsStream("/guest-tests/zelda-public/"+name+".pbs")){assertNotNull(stream);Files.copy(stream,entry);}
|
||||
var t=targets.addObject().put("id",name).put("entrypoint","tests/"+name+"/main.pbs").put("logTag",41003);
|
||||
t.putArray("sourceRoots").add("src").add("tests/"+name);t.putArray("supportRoots");t.putArray("exclusions").add("src/main.pbs");
|
||||
var cases=t.putArray("cases");if(name.equals("writer")){cases.add("purchase").add("commit");}else cases.add("readback");
|
||||
}
|
||||
mapper.writeValue(root.resolve("prometeu.json").toFile(),manifest);
|
||||
Path personal=root.resolve(".studio/memcard.pmc");Files.createDirectories(personal.getParent());Files.writeString(personal,"Unrelated personal image");byte[] personalBytes=Files.readAllBytes(personal);
|
||||
try(var app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(true).run()) {
|
||||
var project=app.getBean(ProjectCatalog.class).openProject(root);app.getBean(ProjectLocalStudioSetupStore.class).save(project,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
|
||||
try(var session=app.getBean(ProjectSessionFactory.class).open(project)) {
|
||||
var service=app.getBean(GuestTestTools.class);
|
||||
service.start(root,null,"writer",new GuestTestTools.Request("writer",1500,1,120_000,GuestTestTools.Media.disposable_create,null,false));
|
||||
var writer=await(service,"writer");
|
||||
Path output=Path.of("build/guest-tests-qualification/zelda-public");Files.createDirectories(output);
|
||||
mapper.writeValue(output.resolve("writer.json").toFile(),writer.result());
|
||||
assertEquals(GuestTests.CaseState.passed,writer.result().verdict(),String.valueOf(writer.result()));assertFalse(writer.runtimeRetained());
|
||||
Path image=root.resolve(".studio/test-runs").resolve(writer.runId()).resolve("memcard.pmc");assertTrue(Files.isRegularFile(image));
|
||||
String afterWriter=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(image)));
|
||||
Files.copy(image,output.resolve("writer-memcard.pmc"),StandardCopyOption.REPLACE_EXISTING);
|
||||
service.start(root,null,"reader",new GuestTestTools.Request("reader",30,1,120_000,GuestTestTools.Media.disposable_reopen,writer.runId(),false));
|
||||
var reader=await(service,"reader");mapper.writeValue(output.resolve("reader.json").toFile(),reader.result());
|
||||
Path cartridge=root.resolve(".studio/test-builds/reader").resolve(reader.result().buildId());
|
||||
try(var files=Files.walk(cartridge)){for(var file:files.toList()){Path dest=output.resolve("reader-cartridge").resolve(cartridge.relativize(file));if(Files.isDirectory(file))Files.createDirectories(dest);else Files.copy(file,dest,StandardCopyOption.REPLACE_EXISTING);}}
|
||||
mapper.writeValue(output.resolve("source-and-media-proof.json").toFile(),Map.of("originalProject",original.toString(),"originalSourcesBefore",before,"originalSourcesAfter",sources(original),"copySourcesAfter",sources(root),"writerImageSha256",afterWriter,"readerImageSha256",HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(image))),"scope","Existing public Inventory.restore_slots, CaveSupplyShop.purchase and SaveStore boot/begin/poll/load. No original generator/private helper/source/barrel edit."));
|
||||
assertEquals(GuestTests.CaseState.passed,reader.result().verdict(),String.valueOf(reader.result()));
|
||||
assertNotEquals(writer.result().sessionId(),reader.result().sessionId());assertNotEquals(writer.result().buildId(),reader.result().buildId());assertFalse(reader.runtimeRetained());
|
||||
assertArrayEquals(personalBytes,Files.readAllBytes(personal));assertEquals(before,sources(root));assertEquals(before,sources(original));
|
||||
mapper.writeValue(output.resolve("writer.json").toFile(),writer.result());mapper.writeValue(output.resolve("reader.json").toFile(),reader.result());
|
||||
mapper.writeValue(output.resolve("source-and-media-proof.json").toFile(),Map.of("originalProject",original.toString(),"originalSourcesBefore",before,"originalSourcesAfter",sources(original),"copySourcesAfter",sources(root),"writerImageSha256",afterWriter,"readerImageSha256",HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(image))),"scope","Existing public Inventory.restore_slots, CaveSupplyShop.purchase and SaveStore boot/begin/poll/load. No original generator/private helper/source/barrel edit."));
|
||||
}
|
||||
}
|
||||
}
|
||||
GuestTestTools.View await(GuestTestTools service,String id)throws Exception {
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(130);
|
||||
while(System.nanoTime()<end){var view=service.get(root,null,new OperationLookup(null,id));if(view.workerTerminated())return view;Thread.sleep(10);}
|
||||
throw new AssertionError("Pilot test worker did not terminate");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.stage.Stage;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.app.StudioApplicationConfiguration;
|
||||
import p.studio.app.mcp.*;
|
||||
import p.studio.core.project.ProjectLocalStudioSetupStore;
|
||||
import p.studio.ui.javafx.events.StudioEventBus;
|
||||
import p.studio.ui.javafx.utilities.ThemeService;
|
||||
import p.studio.ui.javafx.workspaces.tests.TestsWorkspace;
|
||||
import java.net.http.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Supplier;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual Tests workspace + authenticated HTTP MCP + installed provider, over one service. */
|
||||
class GuestTestsDesktopTest {
|
||||
@TempDir Path root;
|
||||
@BeforeAll static void toolkit()throws Exception {var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(10,TimeUnit.SECONDS);}
|
||||
@AfterAll static void stopToolkit(){Platform.exit();}
|
||||
static <T>T fx(Supplier<T> work)throws Exception {var value=new CompletableFuture<T>();Platform.runLater(()->{try{value.complete(work.get());}catch(Throwable error){value.completeExceptionally(error);}});return value.get(10,TimeUnit.SECONDS);}
|
||||
@Test void manualRunAndAgentRunShareCasesTranscriptAndOriginalEvidenceWhileGrantBlocksHumanMutation()throws Exception {
|
||||
root=root.toRealPath();String prefix="pbs:example:game:1:isolated-tests/";
|
||||
for(var reference:p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1,p.studio.AppMode.Game))if(reference.id().startsWith(prefix)) {
|
||||
Path dest=root.resolve(reference.id().substring(prefix.length()));Files.createDirectories(dest.getParent());Files.writeString(dest,reference.text());
|
||||
}
|
||||
try(var app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(false).run()) {
|
||||
var ref=app.getBean(ProjectCatalog.class).openProject(root);String install=System.getProperty("studio.test.runtimeInstall","");assertFalse(install.isBlank());
|
||||
app.getBean(ProjectLocalStudioSetupStore.class).save(ref,new ProjectLocalStudioSetup(install,null));
|
||||
try(var project=app.getBean(ProjectSessionFactory.class).open(ref);var client=HttpClient.newHttpClient()) {
|
||||
var tools=app.getBean(GuestTestTools.class);assertSame(tools,project.guestTestTools().orElseThrow());
|
||||
var workspace=fx(()->new TestsWorkspace(project,tools,app.getBean("studioExecutor",ExecutorService.class),app.getBean(StudioEventBus.class)));
|
||||
var stage=fx(()->{var s=new Stage();var scene=new Scene((javafx.scene.Parent)workspace.rootNode(),1400,1000);scene.getStylesheets().add(app.getBean(ThemeService.class).getDefaultTheme());s.setScene(scene);s.setTitle("Guest tests — shared FE/MCP qualification");s.show();workspace.load();return s;});
|
||||
try {
|
||||
await(()->fx(()->!((ComboBox<?>)workspace.rootNode().lookup("#tests-target")).getItems().isEmpty()));
|
||||
fx(()->{((ComboBox<String>)workspace.rootNode().lookup("#tests-target")).setValue("life");((Button)workspace.rootNode().lookup("#tests-run")).fire();return null;});
|
||||
await(()->tools.list(root,null).stream().anyMatch(v->v.workerTerminated()&&v.result()!=null&&v.result().verdict()==GuestTests.CaseState.passed));
|
||||
await(()->fx(()->((Label)workspace.rootNode().lookup("#tests-status")).getText().contains("passed")));
|
||||
fx(()->{snapshot(stage,"manual-pass.png");return null;});
|
||||
assertTrue(project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS).success());
|
||||
var mapper=app.getBean(ObjectMapper.class);var server=app.getBean(LocalMcpServer.class);
|
||||
String credential=ProjectConnectionFiles.read(root,mapper).credential();
|
||||
var initialize=rpc(mapper,"initialize");var p=initialize.putObject("params").put("protocolVersion","2025-06-18");p.putObject("capabilities");p.putObject("clientInfo").put("name","tests-desktop").put("version","1");
|
||||
var connected=post(client,server,mapper,credential,null,initialize);String connection=connected.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
var initialized=mapper.createObjectNode().put("jsonrpc","2.0").put("method","notifications/initialized");assertEquals(202,post(client,server,mapper,credential,connection,initialized).statusCode());
|
||||
JsonNode acquired=call(client,server,mapper,credential,connection,"studio_control_acquire",mapper.createObjectNode().put("projectRoot",root.toString()));String task=acquired.path("taskId").asText();assertFalse(task.isBlank());
|
||||
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("clientRequestId","agent-known-fail");
|
||||
args.set("request",mapper.valueToTree(new GuestTestTools.Request("life-fail",120,1,30_000,GuestTestTools.Media.memory_fresh,null,false)));
|
||||
var receipt=call(client,server,mapper,credential,connection,"studio_tests_start",args);
|
||||
var duplicate=call(client,server,mapper,credential,connection,"studio_tests_start",args);assertEquals(receipt.path("operationId"),duplicate.path("operationId"));
|
||||
var lookup=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("clientRequestId","agent-known-fail");
|
||||
await(()->tools.get(root,task,new OperationLookup(null,"agent-known-fail")).workerTerminated());
|
||||
var result=call(client,server,mapper,credential,connection,"studio_tests_get",lookup);
|
||||
assertEquals("failed",result.path("result").path("verdict").asText());
|
||||
var core=tools.get(root,task,new OperationLookup(null,"agent-known-fail"));
|
||||
var coreSummary=(ObjectNode)mapper.readTree(mapper.writeValueAsString(core.result()));coreSummary.remove("transcript");assertEquals(coreSummary,result.path("result"));assertEquals(8,result.path("transcriptTotal").asInt());
|
||||
var page=call(client,server,mapper,credential,connection,"studio_tests_transcript",lookup.deepCopy().put("offset",0).put("limit",128));assertEquals(8,page.path("events").size());
|
||||
assertEquals(mapper.readTree(mapper.writeValueAsString(core.result().transcript())),page.path("events"));
|
||||
await(()->fx(()->((Button)workspace.rootNode().lookup("#tests-run")).isDisabled()));
|
||||
await(()->fx(()->((ListView<?>)workspace.rootNode().lookup("#tests-history")).getItems().size()==2));
|
||||
fx(()->{((ListView<?>)workspace.rootNode().lookup("#tests-history")).getSelectionModel().selectLast();return null;});
|
||||
await(()->fx(()->((Label)workspace.rootNode().lookup("#tests-status")).getText().contains("failed")));
|
||||
fx(()->{assertTrue(((Button)workspace.rootNode().lookup("#tests-cancel")).isDisabled());assertFalse(((TreeView<?>)workspace.rootNode().lookup("#tests-cases")).isDisabled());snapshot(stage,"agent-known-fail.png");return null;});
|
||||
Path output=Path.of("build/guest-tests-qualification/desktop");Files.createDirectories(output);mapper.writeValue(output.resolve("mcp-failed-result.json").toFile(),result);mapper.writeValue(output.resolve("mcp-transcript.json").toFile(),page);
|
||||
project.automation().reclaim().toCompletableFuture().get(5,TimeUnit.SECONDS);
|
||||
} finally {fx(()->{workspace.unLoad();stage.close();return null;});}
|
||||
}
|
||||
}
|
||||
}
|
||||
static ObjectNode rpc(ObjectMapper mapper,String method){return mapper.createObjectNode().put("jsonrpc","2.0").put("id",UUID.randomUUID().toString()).put("method",method);}
|
||||
static HttpResponse<String> post(HttpClient client,LocalMcpServer server,ObjectMapper mapper,String token,String connection,JsonNode body)throws Exception {
|
||||
var request=HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15)).header("Authorization","Bearer "+token).header("Content-Type","application/json").header("Accept","application/json, text/event-stream").header("MCP-Protocol-Version","2025-06-18");
|
||||
if(connection!=null)request.header("Mcp-Session-Id",connection);
|
||||
return client.send(request.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body))).build(),HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
static JsonNode call(HttpClient client,LocalMcpServer server,ObjectMapper mapper,String token,String connection,String tool,ObjectNode args)throws Exception {
|
||||
var body=rpc(mapper,"tools/call");body.putObject("params").put("name",tool).set("arguments",args);var response=post(client,server,mapper,token,connection,body);
|
||||
assertEquals(200,response.statusCode());var parsed=mapper.readTree(response.body());assertFalse(parsed.has("error"),parsed.toString());var result=parsed.path("result");assertFalse(result.path("isError").asBoolean(),result.toString());return result.path("structuredContent").path("value");
|
||||
}
|
||||
static void snapshot(Stage stage,String name) {
|
||||
var picture=stage.getScene().snapshot(null);var image=new java.awt.image.BufferedImage((int)picture.getWidth(),(int)picture.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,picture.getPixelReader().getArgb(x,y));
|
||||
try{Path output=Path.of("build/guest-tests-qualification/desktop");Files.createDirectories(output);javax.imageio.ImageIO.write(image,"png",output.resolve(name).toFile());}catch(Exception error){throw new RuntimeException(error);}
|
||||
}
|
||||
interface Check {boolean get()throws Exception;}
|
||||
static void await(Check condition)throws Exception {long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(30);while(System.nanoTime()<end){if(condition.get())return;Thread.sleep(10);}fail("Desktop/shared service condition did not converge");}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.app.StudioApplicationConfiguration;
|
||||
import p.studio.core.project.ProjectLocalStudioSetupStore;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual installed provider and PBS/compiler/packer/shared runner; no simulated protocol. */
|
||||
class GuestTestsInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
ConfigurableApplicationContext app;ProjectSession session;GuestTestTools tests;ObjectMapper mapper;String task;
|
||||
@BeforeEach void open()throws Exception {
|
||||
root=root.toRealPath();String install=System.getProperty("studio.test.runtimeInstall","");assertFalse(install.isBlank(),"Select an installed protocol 1.2 runtime");
|
||||
String prefix="pbs:example:game:1:isolated-tests/";
|
||||
for(var ref:p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1,p.studio.AppMode.Game)) {
|
||||
if(ref.id().startsWith(prefix)){Path dest=root.resolve(ref.id().substring(prefix.length()));Files.createDirectories(dest.getParent());Files.writeString(dest,ref.text());}
|
||||
}
|
||||
app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(true).run();
|
||||
var project=app.getBean(ProjectCatalog.class).openProject(root);
|
||||
app.getBean(ProjectLocalStudioSetupStore.class).save(project,new ProjectLocalStudioSetup(install,null));
|
||||
session=app.getBean(ProjectSessionFactory.class).open(project);tests=app.getBean(GuestTestTools.class);mapper=app.getBean(ObjectMapper.class);
|
||||
}
|
||||
@AfterEach void close(){try{if(session!=null)session.close();}finally{if(app!=null)app.close();}}
|
||||
GuestTestTools.Request request(String target,long maxFrames){return new GuestTestTools.Request(target,maxFrames,1,30_000,GuestTestTools.Media.memory_fresh,null,false);}
|
||||
GuestTestTools.View await(String request)throws Exception {
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(40);
|
||||
do {var result=tests.get(root,task,new OperationLookup(null,request));if(result.workerTerminated())return result;Thread.sleep(5);}while(System.nanoTime()<deadline);
|
||||
throw new AssertionError("Guest test worker did not terminate");
|
||||
}
|
||||
@Test void realLifePassAndDeliberateFailureHaveSeparateFreshSessionsAndPreserveProductionAndUserMedia()throws Exception {
|
||||
var production=Files.readAllBytes(root.resolve("src/main.pbs"));var barrel=Files.readAllBytes(root.resolve("src/mod.barrel"));
|
||||
Path personal=root.resolve(".studio/memcard.pmc");Files.createDirectories(personal.getParent());Files.writeString(personal,"personal image must remain byte identical");byte[] personalBytes=Files.readAllBytes(personal);
|
||||
session.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=app.getBean(TaskTools.class).acquire(root).task().value();
|
||||
assertEquals(2,tests.targets(root,task).targets().size());var started=tests.start(root,task,"pass",request("life",20));
|
||||
assertEquals(started.operation().id(),tests.start(root,task,"pass",request("life",20)).operation().id());
|
||||
assertEquals(AutomationFailure.Code.CLIENT_REQUEST_CONFLICT,assertThrows(AutomationException.class,()->tests.start(root,task,"pass",request("life-fail",20))).failure().code());
|
||||
var passed=await("pass");assertNotNull(passed.result());assertEquals(GuestTests.CaseState.passed,passed.result().verdict(),String.valueOf(passed.result()));
|
||||
assertEquals(8,passed.result().transcript().size());assertEquals(2,passed.result().cases().size());assertEquals(true,passed.result().context().get("runtimeClosed"));
|
||||
assertNotNull(passed.result().context().get("captureArtifactId"));
|
||||
tests.start(root,task,"fail",request("life-fail",20));var failed=await("fail");
|
||||
assertEquals(GuestTests.CaseState.failed,failed.result().verdict(),String.valueOf(failed.result()));assertNull(failed.result().failure());
|
||||
assertNotEquals(passed.result().sessionId(),failed.result().sessionId());assertNotEquals(passed.result().buildId(),failed.result().buildId());
|
||||
assertEquals(GuestTests.CaseState.failed,failed.result().cases().getFirst().state());
|
||||
assertEquals(8,tests.transcript(root,task,new OperationLookup(null,"pass"),0,128).total());
|
||||
assertArrayEquals(personalBytes,Files.readAllBytes(personal));assertArrayEquals(production,Files.readAllBytes(root.resolve("src/main.pbs")));assertArrayEquals(barrel,Files.readAllBytes(root.resolve("src/mod.barrel")));
|
||||
assertTrue(Files.isRegularFile(root.resolve(".studio/test-runs").resolve(passed.runId()).resolve("result.json")));
|
||||
var output=Path.of("build/guest-tests-qualification");Files.createDirectories(output);mapper.writeValue(output.resolve("life-pass.json").toFile(),passed.result());mapper.writeValue(output.resolve("life-known-fail.json").toFile(),failed.result());
|
||||
String artifact=String.valueOf(passed.result().context().get("captureArtifactId"));
|
||||
String checkpointSource="import { Log } from @sdk:log;\ndeclare global tick: int=0;\n[Frame] fn frame() -> void { if tick==0 {"
|
||||
+emit("suite_start",0,null,Map.of())+emit("case_start",1,"image",Map.of())
|
||||
+emit("assertion",2,"image",Map.of("name","reference","message","Retained checkpoint","passed",true))
|
||||
+emit("checkpoint",3,"image",Map.of("artifactId",artifact))+"} else if tick==1 {"
|
||||
+emit("case_end",4,"image",Map.of())+emit("suite_end",5,null,Map.of("eventCount",6))+"} tick+=1; }\n";
|
||||
addTarget("checkpoint",checkpointSource,List.of("image"));tests.start(root,task,"checkpoint",request("checkpoint",20));var checkpoint=await("checkpoint");
|
||||
assertEquals(GuestTests.CaseState.passed,checkpoint.result().verdict(),String.valueOf(checkpoint.result()));assertEquals(List.of(artifact),checkpoint.result().cases().getFirst().checkpointIds());
|
||||
var original=app.getBean(EvidenceTools.class).metadata(root,task,artifact).artifact();
|
||||
assertEquals(passed.result().sessionId(),original.provenance().get("sessionId"));assertEquals(passed.operation().id().value(),original.provenance().get("operationId"));assertNotEquals(checkpoint.result().sessionId(),original.provenance().get("sessionId"));
|
||||
mapper.writeValue(output.resolve("original-checkpoint-reference.json").toFile(),checkpoint.result());
|
||||
var ordinary=app.getBean(TaskTools.class);ordinary.build(root,task,"production-after-test");
|
||||
TrackedOperation built;do{built=ordinary.operation(root,task,new OperationLookup(null,"production-after-test"));Thread.sleep(5);}while(!built.workerTerminated());
|
||||
assertTrue(built.buildResult().success(),built.buildResult().diagnostics().toString());assertEquals("production",built.buildResult().context().get("targetId"));
|
||||
ordinary.headless(root,task,TaskTools.HeadlessAction.BOOT,built.buildId(),Map.of());ordinary.advance(root,task,"ordinary-frame",1);
|
||||
TrackedOperation frame;do{frame=ordinary.operation(root,task,new OperationLookup(null,"ordinary-frame"));Thread.sleep(5);}while(!frame.workerTerminated());
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED,frame.runtimeResult().kind());ordinary.headless(root,task,TaskTools.HeadlessAction.SHUTDOWN,null,Map.of());
|
||||
app.getBean(TaskTools.class).release(root,task).toCompletableFuture().get(5,TimeUnit.SECONDS);
|
||||
assertThrows(ControlDeniedException.class,()->tests.get(root,task,new OperationLookup(null,"pass")));
|
||||
assertEquals(GuestTests.CaseState.passed,tests.get(root,null,new OperationLookup(null,"pass")).result().verdict());
|
||||
}
|
||||
void addTarget(String id,String source,List<String> cases)throws Exception {
|
||||
Path path=root.resolve("tests/"+id+"/main.pbs");Files.createDirectories(path.getParent());Files.writeString(path,source);
|
||||
var manifest=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(root.resolve("prometeu.json").toFile());
|
||||
var array=(com.fasterxml.jackson.databind.node.ArrayNode)manifest.path("testTargets").path("targets");
|
||||
var target=array.addObject().put("id",id).put("entrypoint","tests/"+id+"/main.pbs").put("logTag",41000);
|
||||
target.putArray("sourceRoots").add("src").add("tests/"+id);target.putArray("supportRoots");target.putArray("exclusions").add("src/main.pbs");target.set("cases",mapper.valueToTree(cases));mapper.writeValue(root.resolve("prometeu.json").toFile(),manifest);
|
||||
}
|
||||
@Test void timeoutAndCancellationFinishWorkersWithoutInventingASuccessfulSuite()throws Exception {
|
||||
addTarget("waiting","[Frame] fn frame() -> void {}\n",List.of("never"));
|
||||
tests.start(root,null,"timeout",request("waiting",1));var timeout=await("timeout");
|
||||
assertEquals(GuestTests.Completion.timed_out,timeout.result().completion());assertEquals(GuestTests.CaseState.not_run,timeout.result().cases().getFirst().state());assertFalse(timeout.runtimeRetained());
|
||||
var started=tests.start(root,null,"cancel",request("waiting",100_000));
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);
|
||||
while(tests.get(root,null,new OperationLookup(null,"cancel")).progress().completedFrames()<2&&System.nanoTime()<end)Thread.sleep(5);
|
||||
assertTrue(tests.cancel(root,null,started.operation().id().value()));var cancelled=await("cancel");
|
||||
assertEquals(GuestTests.Completion.cancelled,cancelled.result().completion());assertFalse(cancelled.runtimeRetained());
|
||||
assertEquals(0,session.automation().snapshot().manualOperations());
|
||||
}
|
||||
@Test void droppedGuestAssertionWithContiguousNativeLogsIsRejected()throws Exception {
|
||||
String first="{\"schemaVersion\":1,\"suiteId\":\"drop\",\"eventId\":\"s\",\"kind\":\"suite_start\",\"payload\":{\"ordinal\":0}}";
|
||||
var events=new ArrayList<String>();events.add(first);
|
||||
events.add("{\"schemaVersion\":1,\"suiteId\":\"drop\",\"caseId\":\"check\",\"eventId\":\"c\",\"kind\":\"case_start\",\"payload\":{\"ordinal\":1}}");
|
||||
events.add("{\"schemaVersion\":1,\"suiteId\":\"drop\",\"caseId\":\"check\",\"eventId\":\"a\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":2,\"name\":\"kept\",\"message\":\"kept\",\"passed\":true}}");
|
||||
String dropped=events.getLast().replace("\"a\"","\"lost\"").replace("\"ordinal\":2","\"ordinal\":3").replace("\"passed\":true","\"passed\":false");
|
||||
var source=new StringBuilder("import { Log } from @sdk:log;\ndeclare global tick: int=0;\n[Frame] fn frame() -> void { if tick==0 {\n");
|
||||
for(var event:events)source.append("Log.info(41000,").append(mapper.writeValueAsString(event)).append(");\n");
|
||||
source.append("for i: int from 0 until 7 { Log.info(0,\"ordinary\"); }\nLog.info(41000,").append(mapper.writeValueAsString(dropped)).append(");\n} else if tick==1 {\n");
|
||||
String endCase="{\"schemaVersion\":1,\"suiteId\":\"drop\",\"caseId\":\"check\",\"eventId\":\"ce\",\"kind\":\"case_end\",\"payload\":{\"ordinal\":4}}";
|
||||
String endSuite="{\"schemaVersion\":1,\"suiteId\":\"drop\",\"eventId\":\"se\",\"kind\":\"suite_end\",\"payload\":{\"ordinal\":5,\"eventCount\":6}}";
|
||||
source.append("Log.info(41000,").append(mapper.writeValueAsString(endCase)).append(");Log.info(41000,").append(mapper.writeValueAsString(endSuite)).append(");\n} tick+=1; }\n");
|
||||
addTarget("drop",source.toString(),List.of("check"));tests.start(root,null,"drop-test",request("drop",20));var result=await("drop-test").result();
|
||||
assertEquals(GuestTests.CaseState.infrastructure_failure,result.verdict(),String.valueOf(result));
|
||||
assertTrue(result.failure().message().contains("ordinal"),result.failure().message());assertFalse(result.lossDetected());
|
||||
assertEquals(1,result.cases().getFirst().assertions().size());assertTrue(result.cases().getFirst().assertions().getFirst().passed());
|
||||
var output=Path.of("build/guest-tests-qualification");Files.createDirectories(output);mapper.writeValue(output.resolve("producer-drop-rejected.json").toFile(),result);
|
||||
String emptySource="import { Log } from @sdk:log;\ndeclare global tick: int=0;\n[Frame] fn frame() -> void { if tick==0 {"
|
||||
+emit("suite_start",0,null,Map.of())+emit("suite_end",1,null,Map.of("eventCount",2))+"} tick+=1; }\n";
|
||||
addTarget("empty",emptySource,List.of());tests.start(root,null,"empty",request("empty",20));var empty=await("empty").result();
|
||||
assertEquals(GuestTests.CaseState.infrastructure_failure,empty.verdict());assertTrue(empty.failure().message().contains("Empty suite"));
|
||||
mapper.writeValue(output.resolve("empty-suite-rejected.json").toFile(),empty);
|
||||
}
|
||||
String emit(String kind,int ordinal,String caseId,Map<String,Object> payload)throws Exception {
|
||||
var event=mapper.createObjectNode().put("schemaVersion",1).put("suiteId","dirty").put("eventId","e"+ordinal).put("kind",kind);
|
||||
if(caseId!=null)event.put("caseId",caseId);var values=new LinkedHashMap<>(payload);values.put("ordinal",ordinal);event.set("payload",mapper.valueToTree(values));
|
||||
String message=mapper.writeValueAsString(event);assertTrue(message.getBytes(java.nio.charset.StandardCharsets.UTF_8).length<=256);
|
||||
return "Log.info(41000,"+mapper.writeValueAsString(message)+");";
|
||||
}
|
||||
@Test void nativeDirtyRefusalRetainsRuntimeUntilExplicitDiscardWithoutChangingOriginalResult()throws Exception {
|
||||
var manifest=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(root.resolve("prometeu.json").toFile());manifest.put("memcard_slots",1);mapper.writeValue(root.resolve("prometeu.json").toFile(),manifest);
|
||||
String source="import { Log } from @sdk:log;\nimport { Mem, MemcardBuffer } from @sdk:mem;\ndeclare global context: long=0;\ndeclare global tick: int=0;\n"
|
||||
+"[MemcardBoot] fn boot_card(value: long) -> int { context=value; if Mem.presentation(value,\"Dirty test\",1 as long,1,1,new MemcardBuffer(560),0,560)!=0 as long { return 1; } return 0; }\n[Frame] fn frame() -> void { if tick==0 {"
|
||||
+emit("suite_start",0,null,Map.of())+emit("case_start",1,"write",Map.of())+"} else if tick==1 { let bytes=new MemcardBuffer(1);bytes.write(0,7);let write=Mem.slot_write(context,0,0,bytes,0,1);if write.status==0 as long {"
|
||||
+emit("assertion",2,"write",Map.of("name","RAM write","message","native write accepted","passed",true))+"} else {"
|
||||
+emit("assertion",2,"write",Map.of("name","RAM write","message","native write accepted","passed",false))+"}"
|
||||
+emit("case_end",3,"write",Map.of())+"} else if tick==2 {"+emit("suite_end",4,null,Map.of("eventCount",5))+"} tick+=1; }\n";
|
||||
addTarget("dirty",source,List.of("write"));tests.start(root,null,"dirty-run",request("dirty",20));var run=await("dirty-run");
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR,run.result().failure().code(),String.valueOf(run.result()));assertTrue(run.runtimeRetained());
|
||||
assertEquals(GuestTests.CaseState.passed,run.result().cases().getFirst().state());assertEquals(false,run.result().context().get("runtimeClosed"));
|
||||
assertEquals(ControlResult.Status.BUSY,session.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS).status());
|
||||
assertThrows(AutomationException.class,()->tests.shutdown(root,null,run.operation().id().value(),false));
|
||||
tests.shutdown(root,null,run.operation().id().value(),true);var recovered=tests.get(root,null,new OperationLookup(null,"dirty-run"));
|
||||
assertFalse(recovered.runtimeRetained());assertSame(run.result(),recovered.result());assertFalse(session.automation().runtimeAttached());
|
||||
assertTrue(session.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS).success());
|
||||
}
|
||||
@Test void manualTestUsesTheSameRunnerAndBlocksGrantUntilTermination()throws Exception {
|
||||
tests.start(root,null,"manual-life",request("life",20));var run=await("manual-life");
|
||||
assertEquals(GuestTests.CaseState.passed,run.result().verdict(),String.valueOf(run.result()));
|
||||
assertFalse(session.automation().runtimeAttached());assertEquals(0,session.automation().snapshot().manualOperations());
|
||||
assertTrue(session.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS).success());
|
||||
assertThrows(ControlDeniedException.class,()->tests.start(root,null,"denied",request("life",20)));
|
||||
}
|
||||
}
|
||||
@@ -66,11 +66,21 @@ public final class HeadlessFixture {
|
||||
emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", "fixture").put("requestId", id).set("error", error));
|
||||
} else response(id, state());
|
||||
}
|
||||
case "get_state" -> { if (!mode.equals("hang-call")) response(id, state()); }
|
||||
case "get_state" -> {
|
||||
if (mode.equals("watchdog-inspection-fails")) {
|
||||
var error = MAPPER.createObjectNode().put("code", "busy").put("message", "Inspection unavailable"); error.putObject("details");
|
||||
emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", "fixture").put("requestId", id).set("error", error));
|
||||
} else if (!mode.equals("hang-call")) response(id, state());
|
||||
}
|
||||
case "get_fault" -> response(id, MAPPER.nullNode());
|
||||
case "get_memcard_state", "memcard_mount", "memcard_unmount", "memcard_reconcile", "memcard_continue_in_memory" -> response(id, memcardState());
|
||||
case "advance" -> {
|
||||
active = id; frames = request.path("params").path("frames").longValue();
|
||||
if (mode.startsWith("watchdog")) {
|
||||
var result = MAPPER.createObjectNode().put("requested", frames).put("completed", 0).put("stop", "host_error");
|
||||
result.putObject("error").put("code", "host_tick_watchdog").put("message", "Controlled watchdog").putObject("details").put("hostTickLimit", 7);
|
||||
response(id, result); continue;
|
||||
}
|
||||
emit(MAPPER.createObjectNode().put("type", "progress").put("sessionId", "fixture").put("requestId", id)
|
||||
.put("requested", frames).put("completed", mode.equals("bad-progress") ? frames + 1 : 2));
|
||||
if (mode.equals("crash")) System.exit(23);
|
||||
@@ -83,6 +93,10 @@ public final class HeadlessFixture {
|
||||
response(active, MAPPER.createObjectNode().put("requested", frames).put("completed", 2).put("stop", "canceled"));
|
||||
}
|
||||
case "capture" -> {
|
||||
if (mode.startsWith("watchdog")) {
|
||||
var error = MAPPER.createObjectNode().put("code", "no_frame_available").put("message", "No completed frame"); error.putObject("details");
|
||||
emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", "fixture").put("requestId", id).set("error", error)); continue;
|
||||
}
|
||||
var image = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
image.setRGB(0, 0, 0xff123456); var bytes = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(image, "png", bytes);
|
||||
response(id, MAPPER.createObjectNode().put("mimeType", "image/png").put("encoding", "base64").put("pixelFormat", "RGBA8888")
|
||||
|
||||
@@ -32,11 +32,14 @@ class HeadlessInstalledRuntimeTest {
|
||||
setup.save(project, new ProjectLocalStudioSetup(install, null));
|
||||
try (var workers = Executors.newSingleThreadExecutor(); var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) {
|
||||
var build = new StudioShipperService(new CompilerBuildGatewayAdapter(), packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers))
|
||||
.withAssetPreflight(new p.studio.app.assets.AssetBudgetInspection(mapper,packer.workspaceService(),setup::load))
|
||||
.prepare(project, ignored -> {}).completion().toCompletableFuture().get(15, TimeUnit.SECONDS);
|
||||
assertTrue(build.success(), build.diagnostics().toString());
|
||||
var gateway = new HeadlessProcessGateway(mapper, setup::load);
|
||||
var session = (HeadlessProcessSession) gateway.boot(project, "real-build", build);
|
||||
try {
|
||||
assertEquals(RuntimeObservation.Lifecycle.BOOTED, session.observation().lifecycle());
|
||||
assertNotNull(session.bootReply().values().get("state"));
|
||||
assertEquals(600, session.maxFramesPerAdvance());
|
||||
assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class,
|
||||
() -> session.call(TaskTools.HeadlessAction.CAPTURE, Map.of())).failure().code());
|
||||
@@ -54,6 +57,8 @@ class HeadlessInstalledRuntimeTest {
|
||||
session.call(TaskTools.HeadlessAction.SET_INPUT, Map.of("a", true));
|
||||
session.call(TaskTools.HeadlessAction.CLEAR_INPUT, Map.of());
|
||||
session.call(TaskTools.HeadlessAction.RESET, Map.of());
|
||||
assertEquals(RuntimeObservation.Lifecycle.UNBOOTED, session.observation().lifecycle());
|
||||
assertNull(session.observation().lastFrame());
|
||||
assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class,
|
||||
() -> session.call(TaskTools.HeadlessAction.CAPTURE, Map.of())).failure().code());
|
||||
session.call(TaskTools.HeadlessAction.BOOT, Map.of());
|
||||
@@ -64,6 +69,7 @@ class HeadlessInstalledRuntimeTest {
|
||||
() -> session.advance(601, ignored -> {})).failure().code());
|
||||
} finally { session.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS); }
|
||||
assertFalse(session.alive());
|
||||
assertEquals(RuntimeObservation.Lifecycle.TERMINATED, session.observation().lifecycle());
|
||||
var cancellable = (HeadlessProcessSession) new HeadlessProcessGateway(mapper, setup::load,
|
||||
new HeadlessLimits(20000, 65536, 33554432, 5000, 60000, 5000)).boot(project, "cancel-build", build);
|
||||
try {
|
||||
|
||||
@@ -73,7 +73,7 @@ class HeadlessMcpDesktopTest {
|
||||
server = app.getBean(LocalMcpServer.class); client = HttpClient.newHttpClient();
|
||||
fx(() -> {
|
||||
locale = new I18nService(); locale.setLocale(Locale.ENGLISH);
|
||||
dev = new DevWorkspace(reference, project.automation(), locale, new StudioEventBus(), app.getBean(AgentConnectionGuide.class));
|
||||
dev = new DevWorkspace(reference, project.automation(), locale, new StudioEventBus(), app.getBean(AgentConnectionGuide.class), project.diagnosticSources());
|
||||
stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance");
|
||||
stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load();
|
||||
});
|
||||
@@ -144,6 +144,39 @@ class HeadlessMcpDesktopTest {
|
||||
assertArrayEquals(png(call("studio_operation_get", args().put("clientRequestId", "cancel-me"))), project.automation().snapshot().capture().png());
|
||||
}
|
||||
|
||||
@Test void observationInspectorAndHttpDistinguishHistoricalAdvanceCurrentResetAndReturnedControl() throws Exception {
|
||||
acquire(); build("observation-build"); boot();
|
||||
value(call("studio_headless_advance", args().put("clientRequestId", "observed").put("frames", 3)));
|
||||
var finished = value(completed("observed"));
|
||||
assertEquals(3, finished.path("observation").path("progress").path("completedFrames").asInt());
|
||||
assertEquals("observed", finished.path("observation").path("context").path("clientRequestId").asText());
|
||||
var reset = value(call("studio_headless_reset", args()));
|
||||
assertEquals("UNBOOTED", reset.path("observation").path("lifecycle").asText());
|
||||
var queried = value(call("studio_operation_get", args().put("clientRequestId", "observed")));
|
||||
assertEquals(finished.path("observation"), queried.path("observation"));
|
||||
assertEquals("UNBOOTED", queried.path("currentObservation").path("lifecycle").asText());
|
||||
var context = value(call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString())));
|
||||
assertEquals("AGENT_WORKING", context.path("control").path("state").asText());
|
||||
assertEquals("UNBOOTED", context.path("runtime").path("lifecycle").asText());
|
||||
fx(() -> {
|
||||
var tree = (TreeView<?>)dev.rootNode().lookup("#dev-runtime-observation");
|
||||
assertNotNull(tree); assertEquals(3, tree.getRoot().getChildren().size());
|
||||
assertTrue(treeContains(tree.getRoot().getChildren().get(1), "lifecycle: UNBOOTED"));
|
||||
assertTrue(treeContains(tree.getRoot().getChildren().get(0), "state: AGENT_WORKING"));
|
||||
});
|
||||
var released = value(call("studio_control_release", args()));
|
||||
assertEquals("MANUAL", released.path("control").path("state").asText());
|
||||
assertEquals("COMPLETED", released.path("control").path("cleanup").asText());
|
||||
assertTrue(released.path("control").path("taskRevoked").asBoolean());
|
||||
fx(() -> {
|
||||
var tree = (TreeView<?>)dev.rootNode().lookup("#dev-runtime-observation");
|
||||
assertTrue(treeContains(tree.getRoot().getChildren().get(0), "cleanup: COMPLETED"));
|
||||
});
|
||||
}
|
||||
private static boolean treeContains(TreeItem<?> item, String expected) {
|
||||
return expected.equals(item.getValue()) || item.getChildren().stream().anyMatch(child -> treeContains(child, expected));
|
||||
}
|
||||
|
||||
@Test void revokeWaitsForRuntimeAndDocumentRefreshAndRejectsLateCalls() throws Exception {
|
||||
prepareLongRun();
|
||||
value(call("studio_headless_advance", args().put("clientRequestId", "before-revoke").put("frames", 1)));
|
||||
@@ -164,7 +197,11 @@ class HeadlessMcpDesktopTest {
|
||||
String edited = Files.readString(source) + "\n// external edit retained on revoke\n"; Files.writeString(source, edited);
|
||||
startRunning("revoked");
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
|
||||
refreshEntered.get(10, TimeUnit.SECONDS);
|
||||
try { refreshEntered.get(10, TimeUnit.SECONDS); }
|
||||
catch (TimeoutException failure) {
|
||||
throw new AssertionError("Return did not reach document refresh: " + project.automation().snapshot().controlObservation()
|
||||
+ "; runtime=" + project.automation().snapshot().runtimeObservation(), failure);
|
||||
}
|
||||
assertEquals(ControlState.RETURNING_CONTROL, project.automation().snapshot().state());
|
||||
assertFalse(project.automation().snapshot().manualAllowed());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
@@ -280,7 +317,7 @@ class HeadlessMcpDesktopTest {
|
||||
@Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception {
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
grant();
|
||||
assertEquals(22, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertEquals(48, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
|
||||
value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100)));
|
||||
var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000)));
|
||||
@@ -364,7 +401,8 @@ class HeadlessMcpDesktopTest {
|
||||
var raw = oracle.call("capture");
|
||||
var image = call("studio_headless_capture", args());
|
||||
assertArrayEquals(png(result), png(image));
|
||||
assertEquals(value(result).path("capture"), value(image));
|
||||
var imageMetadata = ((ObjectNode)value(image)).deepCopy(); imageMetadata.remove("observation");
|
||||
assertEquals(value(result).path("capture"), imageMetadata);
|
||||
compareCapture(raw, image, logical[i], x[i]);
|
||||
captures.add(raw.deepCopy());
|
||||
var actualState = value(call("studio_headless_state", args())).path("state");
|
||||
|
||||
@@ -18,6 +18,42 @@ class HeadlessProcessSessionTest {
|
||||
var session = new HeadlessProcessSession(process, new ObjectMapper(), HeadlessFixture.limits(mode), "build"); sessions.add(session); return session;
|
||||
}
|
||||
@AfterEach void cleanup() { sessions.forEach(session -> session.abort("test cleanup")); }
|
||||
@Test void structuredTestCapabilityRefusalHappensBeforeInitializeOrBoot()throws Exception {
|
||||
var session=start("normal");
|
||||
var failure=assertThrows(AutomationException.class,()->session.initializeAndBoot(root,root,false,Map.of(),root.resolve("unused.pmc"),true));
|
||||
assertEquals(AutomationFailure.Code.RUNTIME_INCOMPATIBLE,failure.failure().code());
|
||||
assertFalse(Files.exists(root.resolve("requests.jsonl")),"Capability refusal must not execute the guest");
|
||||
}
|
||||
@Test void lifecycleObservationsPreserveFinalFactsAcrossResetBootAndShutdown() throws Exception {
|
||||
var session = start("normal"); session.initializeAndBoot(root);
|
||||
assertEquals(RuntimeObservation.Lifecycle.BOOTED, session.observation().lifecycle());
|
||||
assertEquals(session.bootReply().values().get("state"), session.observation().nativeDetails().get("state"));
|
||||
var finalFrame = session.advance(3, ignored -> {}).observation();
|
||||
assertEquals(3L, finalFrame.progress().completedFrames()); assertNotNull(finalFrame.lastFrame());
|
||||
var reset = session.call(TaskTools.HeadlessAction.RESET, Map.of());
|
||||
assertEquals(RuntimeObservation.Lifecycle.UNBOOTED, ((RuntimeObservation)reset.values().get("observation")).lifecycle());
|
||||
assertNull(session.observation().lastFrame()); assertTrue(session.observation().captureStale());
|
||||
assertEquals(3L, finalFrame.progress().completedFrames()); assertNotNull(finalFrame.lastFrame());
|
||||
session.call(TaskTools.HeadlessAction.BOOT, Map.of());
|
||||
assertEquals(RuntimeObservation.Lifecycle.BOOTED, session.observation().lifecycle());
|
||||
var stopped = session.stop(Map.of()).toCompletableFuture().get(3, TimeUnit.SECONDS);
|
||||
assertEquals(RuntimeObservation.Lifecycle.TERMINATED, ((RuntimeObservation)stopped.values().get("observation")).lifecycle());
|
||||
assertFalse(session.alive());
|
||||
}
|
||||
@Test void failedFollowupPreservesTheNativeWatchdogAndKnownZeroFrames() throws Exception {
|
||||
var session = start("watchdog-inspection-fails"); session.initializeAndBoot(root);
|
||||
var result = session.advance(3, ignored -> {});
|
||||
assertEquals(AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE, result.kind());
|
||||
assertEquals(0, result.completedFrames()); assertNull(result.capture());
|
||||
var observation = result.observation();
|
||||
assertEquals(0L, observation.progress().completedFrames());
|
||||
assertEquals("host_tick_watchdog", ((Map<?, ?>)observation.nativeDetails().get("error")).get("code"));
|
||||
assertEquals(Set.of("capture", "get_state"), observation.unavailable().stream()
|
||||
.map(RuntimeObservation.UnavailableObservation::source).collect(java.util.stream.Collectors.toSet()));
|
||||
assertEquals("BUSY", observation.unavailable().stream().filter(value -> value.source().equals("get_state")).findFirst().orElseThrow().code());
|
||||
assertTrue(session.alive());
|
||||
assertEquals(1, Files.readAllLines(root.resolve("requests.jsonl")).stream().filter(line -> line.contains("\"command\":\"advance\"")).count());
|
||||
}
|
||||
@Test void productionLoadDiagnosticsSurviveBootFailureAndMcpSerialization() throws Exception {
|
||||
var mapper = new ObjectMapper();
|
||||
for (String fixture : List.of("resource", "invalid-role", "retired-opcode", "native", "native-abi", "unknown-native")) {
|
||||
@@ -98,6 +134,9 @@ class HeadlessProcessSessionTest {
|
||||
var known = new AtomicReference<TrackedOperation.Progress>();
|
||||
assertThrows(AutomationException.class, () -> session.advance(30, known::set));
|
||||
assertEquals(2L, known.get().completedFrames()); assertFalse(session.alive());
|
||||
assertEquals(RuntimeObservation.Lifecycle.LOST, session.observation().lifecycle());
|
||||
assertEquals(2L, session.observation().progress().completedFrames());
|
||||
assertTrue(session.observation().recovery().stream().noneMatch(RuntimeObservation.RecoveryAction::automatic));
|
||||
assertThrows(AutomationException.class, () -> session.call(TaskTools.HeadlessAction.STATE, Map.of()));
|
||||
}
|
||||
@Test void deadlinesStopHungCallsAndCancellationPreservesKnownPartialProgress() throws Exception {
|
||||
@@ -126,6 +165,8 @@ class HeadlessProcessSessionTest {
|
||||
for (var mode : List.of("bad-progress", "bad-png")) {
|
||||
var session = start(mode); session.initializeAndBoot(root);
|
||||
assertThrows(AutomationException.class, () -> session.advance(3, ignored -> {})); assertFalse(session.alive());
|
||||
assertEquals(RuntimeObservation.Lifecycle.LOST, session.observation().lifecycle());
|
||||
assertEquals("protocol", ((Map<?, ?>)((Map<?, ?>)session.observation().nativeDetails().get("consumerFailure")).get("details")).get("failureKind"));
|
||||
}
|
||||
}
|
||||
@Test void shutdownEscalatesAndKillsOwnedDescendantsWithoutTouchingUnrelatedProcesses() throws Exception {
|
||||
|
||||
@@ -92,6 +92,137 @@ class HeadlessTaskIntegrationTest {
|
||||
}
|
||||
void authorityRetained() { assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); }
|
||||
|
||||
@Test void originalCaptureEvidenceSurvivesLaterFramesRebuildReleaseAndReopen() throws Exception {
|
||||
call(TaskTools.HeadlessAction.BOOT,successfulBuild("evidence-build"));
|
||||
tasks.advance(root,task,"evidence-frame",1);var original=finished("evidence-frame");
|
||||
var evidence=app.getBean(EvidenceTools.class);
|
||||
var saved=evidence.persist(root,task,"save-original",new OperationLookup(null,"evidence-frame"));
|
||||
var artifact=saved.artifacts().getFirst();
|
||||
assertArrayEquals(original.runtimeResult().capture().png(),evidence.image(root,task,artifact.id()));
|
||||
advance("later-frame");
|
||||
assertEquals(saved,evidence.persist(root,task,"save-original",new OperationLookup(null,"evidence-frame")));
|
||||
assertTrue(evidence.metadata(root,task,artifact.id()).stale());
|
||||
assertEquals(original.runtimeResult().capture().frameId(),artifact.provenance().get("frameId"));
|
||||
// This derived reference has a deliberate wrong sample; independent pixel oracles are tested separately.
|
||||
var codec=new p.studio.app.evidence.PngEvidenceCodec();var pixels=codec.decode(original.runtimeResult().capture().png());
|
||||
byte[] different=pixels.rgba();different[0]=(byte)(Byte.toUnsignedInt(different[0])^1);
|
||||
Path reference=root.resolve("known-different.png");Files.write(reference,codec.encode(new Evidence.Pixels(pixels.width(),pixels.height(),different)));
|
||||
var expected=evidence.importReference(root,task,"import-delta",reference,null).artifacts().getFirst();
|
||||
var report=evidence.compare(root,task,"known-failure",expected.id(),artifact.id(),Evidence.Parameters.exact(Evidence.Alpha.compare));
|
||||
assertEquals(Evidence.Verdict.rejected,report.report().verdict());assertEquals(1,report.report().differentPixels());
|
||||
assertEquals(new Evidence.Rect(0,0,1,1),report.report().boundingBox());
|
||||
successfulBuild("evidence-rebuild");
|
||||
tasks.release(root,task).toCompletableFuture().get(10,TimeUnit.SECONDS);project.close();
|
||||
var ref=app.getBean(ProjectCatalog.class).openProject(root);project=app.getBean(ProjectSessionFactory.class).open(ref);
|
||||
project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tasks.acquire(root).task().value();
|
||||
assertArrayEquals(original.runtimeResult().capture().png(),evidence.image(root,task,artifact.id()));
|
||||
assertEquals(saved,evidence.persist(root,task,"save-original",new OperationLookup(null,"evidence-frame")));
|
||||
System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(Map.of("kind","native-checkpoint","artifact",artifact,"report",report.report(),"nativeAdvanceRequests",2,"persistenceExtraAdvanceOrCaptureRequests",0)));
|
||||
}
|
||||
|
||||
@Test void zeldaPilotUsesDisposableCopyAndKeepsReferenceLimitationsExplicit() throws Exception {
|
||||
Path originalProject=Path.of(System.getProperty("studio.test.zeldaProject", "../../zelda-1")).toAbsolutePath().normalize();
|
||||
assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Zelda pilot checkout is required for this qualification");
|
||||
project.close();Path copy=root.resolve("zelda-pilot");Files.createDirectories(copy);
|
||||
for(String name:List.of("prometeu.json","src","assets")) {
|
||||
Path from=originalProject.resolve(name);
|
||||
if(Files.isDirectory(from))try(var paths=Files.walk(from)) {
|
||||
for(var p:paths.toList()){var target=copy.resolve(originalProject.relativize(p));if(Files.isDirectory(p))Files.createDirectories(target);else Files.copy(p,target);}
|
||||
}else Files.copy(from,copy.resolve(name));
|
||||
}
|
||||
root=copy.toRealPath();var ref=app.getBean(ProjectCatalog.class).openProject(root);
|
||||
app.getBean(ProjectLocalStudioSetupStore.class).save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
|
||||
project=app.getBean(ProjectSessionFactory.class).open(ref);project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tasks.acquire(root).task().value();
|
||||
String build=successfulBuild("zelda-pilot-build");tasks.headless(root,task,TaskTools.HeadlessAction.BOOT,build,Map.of("memcardChoice","memory_fresh"));
|
||||
var evidence=app.getBean(EvidenceTools.class);var measurements=new ArrayList<Map<String,Object>>();
|
||||
var mcp=app.getBean(p.studio.app.mcp.McpToolRegistry.class);
|
||||
long beforeWireBytes=0,afterWireBytes=0;int beforeCalls=0,afterCalls=0;
|
||||
var legacyPaths=new ArrayList<String>();
|
||||
String[] refs={"extracted/inventory_screen/validation/production_start.png","extracted/hud/runtime_initial.png","extracted/bomb_wall/validation/scroll_north_mid.png"};
|
||||
String[] names={"screen","hud","scroll"};
|
||||
long totalPngBytes=0;
|
||||
for(int i=0;i<names.length;i++) {
|
||||
if(i>0)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of(i==1?"start":"right",true));
|
||||
String request="zelda-"+names[i];tasks.advance(root,task,request,i==0?1:i==1?76:120);var operation=finished(request);
|
||||
assertNull(operation.failure());assertNotNull(operation.runtimeResult().capture());
|
||||
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task);
|
||||
var before=mcp.call("studio_operation_get",args.deepCopy().put("clientRequestId",request)).wire();
|
||||
beforeCalls++;beforeWireBytes+=mapper.writeValueAsBytes(before).length;
|
||||
byte[] legacyPng=Base64.getDecoder().decode(before.path("content").get(1).path("data").asText());
|
||||
Path legacyActual=root.resolve("legacy-"+names[i]+".png");Files.write(legacyActual,legacyPng);
|
||||
var persisted=mcp.call("studio_evidence_persist",args.deepCopy().put("clientRequestId","persist-"+request).put("sourceClientRequestId",request)).wire();
|
||||
afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(persisted).length;
|
||||
assertFalse(persisted.path("isError").asBoolean(),persisted.toString());
|
||||
var actual=mapper.convertValue(persisted.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst();
|
||||
Path reference=root.resolve("reference-"+names[i]+".png");Files.copy(originalProject.resolve(refs[i]),reference);
|
||||
legacyPaths.add(reference.toString());legacyPaths.add(legacyActual.toString());
|
||||
var imported=mcp.call("studio_evidence_import",args.deepCopy().put("clientRequestId","import-"+request).put("path",reference.toString())).wire();
|
||||
afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(imported).length;
|
||||
assertFalse(imported.path("isError").asBoolean(),imported.toString());
|
||||
var expected=mapper.convertValue(imported.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst();
|
||||
Evidence.Rect roi=i==1?new Evidence.Rect(112,15,256,56):null;
|
||||
var params=new Evidence.Parameters(roi,List.of(),Evidence.Alpha.compare,0,0);
|
||||
var comparisonArgs=args.deepCopy().put("clientRequestId","compare-"+request).put("expectedId",expected.id()).put("actualId",actual.id());
|
||||
var parametersNode=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.valueToTree(params);
|
||||
if(roi==null)parametersNode.remove("roi");comparisonArgs.set("parameters",parametersNode);
|
||||
var compared=mcp.call("studio_evidence_compare",comparisonArgs).wire();afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(compared).length;
|
||||
assertFalse(compared.path("isError").asBoolean(),compared.toString());
|
||||
var report=mapper.convertValue(compared.path("structuredContent").path("value"),Evidence.Publication.class);
|
||||
totalPngBytes+=legacyPng.length;
|
||||
measurements.add(Map.of("case",names[i],"referencePath",refs[i],"actual",actual,"report",report.report()));
|
||||
}
|
||||
// Execute the former external comparison path against the same checkpoints; count actual calls/bytes/scripts.
|
||||
Path script=root.resolve("LegacyVisualCompare.java");
|
||||
Files.writeString(script,"""
|
||||
import javax.imageio.ImageIO;import java.io.File;
|
||||
class LegacyVisualCompare {public static void main(String[] args)throws Exception {
|
||||
for(int n=0;n<args.length;n+=2) {
|
||||
var a=ImageIO.read(new File(args[n]));var b=ImageIO.read(new File(args[n+1]));long count=0;
|
||||
if(a.getWidth()!=b.getWidth()||a.getHeight()!=b.getHeight())count=-1;
|
||||
else for(int y=0;y<a.getHeight();y++)for(int x=0;x<a.getWidth();x++)if(a.getRGB(x,y)!=b.getRGB(x,y))count++;
|
||||
System.out.println((n/2)+","+count);
|
||||
}
|
||||
}}
|
||||
""");
|
||||
var command=new ArrayList<String>(List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),script.toString()));command.addAll(legacyPaths);
|
||||
var legacy=new ProcessBuilder(command).redirectErrorStream(true).start();assertTrue(legacy.waitFor(30,TimeUnit.SECONDS));
|
||||
String legacyOutput=new String(legacy.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);assertEquals(0,legacy.exitValue(),legacyOutput);
|
||||
var output=Map.of("kind","zelda-pilot","limitations","Saved port captures are contextual references, not an independent NES oracle; screen/HUD/scroll reference labels identify their provenance. Current checkpoints are observations and mismatch is retained as a comparison result.",
|
||||
"results",measurements,"measurement",Map.of("sharedGuestAdvanceRequests",3,"before",Map.of("mcpCalls",beforeCalls,"wireResponseBytes",beforeWireBytes,"imagePngBytes",totalPngBytes,"externalComparisonScripts",1,"externalScriptOutput",legacyOutput),
|
||||
"after",Map.of("mcpCalls",afterCalls,"wireResponseBytes",afterWireBytes,"imageTransferBytesForMetrics",0,"externalComparisonScripts",0),
|
||||
"basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from the explicit HUD ROI by design."));
|
||||
System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(output));
|
||||
}
|
||||
|
||||
@Test void actualWatchdogPreservesNativeCauseZeroProgressAndDoesNotReplayOnLookup() throws Exception {
|
||||
Files.writeString(source, code.replace("fn frame() -> void {", "fn frame() -> void { while (true) { }"));
|
||||
call(TaskTools.HeadlessAction.BOOT, successfulBuild("watchdog-build"));
|
||||
tasks.advance(root, task, "watchdog", 1);
|
||||
var result = finished("watchdog");
|
||||
assertNull(result.failure());
|
||||
assertEquals(AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE, result.runtimeResult().kind());
|
||||
assertEquals(0L, result.progress().completedFrames());
|
||||
assertEquals("watchdog_expired", ((Map<?, ?>)result.observation().nativeDetails().get("error")).get("code"));
|
||||
assertTrue(result.observation().captureStale());
|
||||
assertEquals("watchdog", result.observation().context().get("clientRequestId"));
|
||||
var artifactHashes = new LinkedHashMap<String, String>();
|
||||
for (var file : finished("watchdog-build").buildResult().emittedArtifacts())
|
||||
if (Files.isRegularFile(file)) artifactHashes.put(root.relativize(file).toString(),
|
||||
HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file))));
|
||||
System.out.println("HEADLESS_OBSERVATION " + mapper.writeValueAsString(Map.of(
|
||||
"sourceSha256", HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(source))),
|
||||
"artifacts", artifactHashes, "observation", result.observation().toMap())));
|
||||
var before = call(TaskTools.HeadlessAction.STATE, null).values().get("state");
|
||||
var lookup = tasks.operation(root, task, new OperationLookup(null, "watchdog"));
|
||||
assertEquals(result.observation(), lookup.observation());
|
||||
assertEquals(before, call(TaskTools.HeadlessAction.STATE, null).values().get("state"));
|
||||
assertNull(call(TaskTools.HeadlessAction.FAULT, null).values().get("fault"));
|
||||
authorityRetained();
|
||||
Files.writeString(source, code);
|
||||
call(TaskTools.HeadlessAction.BOOT, successfulBuild("corrected-watchdog"));
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("after-watchdog").kind());
|
||||
}
|
||||
|
||||
@Test void savedEditsRebuildRealArtifactsAndCorrelateDevWithoutSnapshots() throws Exception {
|
||||
assertTrue(diagnostics().isEmpty());
|
||||
assertThrows(ControlDeniedException.class, () -> app.getBean(Shipper.class).prepare(project.projectReference(), ignored -> {}));
|
||||
@@ -103,6 +234,10 @@ class HeadlessTaskIntegrationTest {
|
||||
assertArrayEquals(initial.capture().png(), project.automation().snapshot().capture().png());
|
||||
call(TaskTools.HeadlessAction.RESET, null);
|
||||
assertTrue(project.automation().snapshot().stale());
|
||||
assertEquals(RuntimeObservation.Lifecycle.UNBOOTED, project.automation().snapshot().runtimeObservation().lifecycle());
|
||||
var historical = finished("initial").observation();
|
||||
assertEquals(first, historical.buildId()); assertEquals(3L, historical.progress().completedFrames());
|
||||
assertNotEquals(historical.lifecycle(), finished("initial").currentObservation().lifecycle());
|
||||
assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class,
|
||||
() -> call(TaskTools.HeadlessAction.CAPTURE, null)).failure().code());
|
||||
assertEquals(session, call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId"));
|
||||
@@ -151,6 +286,7 @@ class HeadlessTaskIntegrationTest {
|
||||
var fault = advance("fault");
|
||||
assertEquals(AutomationOutcome.Kind.GUEST_FAULT, fault.kind());
|
||||
assertFalse(fault.diagnostics().isEmpty());
|
||||
assertNotNull(fault.observation().nativeDetails().get("fault"));
|
||||
assertNotNull(call(TaskTools.HeadlessAction.FAULT, null).values().get("fault"));
|
||||
authorityRetained();
|
||||
|
||||
|
||||
@@ -80,9 +80,12 @@ class MemcardInstalledRuntimeTest {
|
||||
""".formatted(version));
|
||||
Files.writeString(projectRoot.resolve("src/mod.barrel"), "pub fn frame() -> void;");
|
||||
Files.writeString(projectRoot.resolve("src/main.pbs"), source);
|
||||
CompilerBuildGateway compiler = (project, log) -> {
|
||||
CompilerBuildGateway compiler = new CompilerBuildGateway(){
|
||||
public CompilerBuildOutput compile(ProjectReference project,java.util.function.Consumer<String> log){return compile(project,BuildSelection.productionBuild(),project.rootPath().resolve("build"),log);}
|
||||
public CompilerBuildOutput compile(ProjectReference project,BuildSelection selection,Path output,java.util.function.Consumer<String> log){
|
||||
var admitted=new p.studio.app.compiler.CompilerBuildGatewayAdapter().compile(project,selection,output,log);
|
||||
var result = BuilderPipelineService.INSTANCE.build(BuilderPipelineContext.fromConfig(
|
||||
new BuilderPipelineConfig(false, project.rootPath().toString())), LogAggregator.with(log));
|
||||
new BuilderPipelineConfig(false, project.rootPath().toString(),"core-v1",p.studio.compiler.utilities.SourceProviderFactory.filesystem(),selection.targetId(),output)), LogAggregator.with(log));
|
||||
var compiled = result.compileResult();
|
||||
var program = optimized ? compiled.optimizedIrvm() : compiled.irvm();
|
||||
var module = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
@@ -91,12 +94,13 @@ class MemcardInstalledRuntimeTest {
|
||||
try { Files.write(result.bytecodeArtifactPath(), module.serialize()); }
|
||||
catch (java.io.IOException failure) { throw new java.io.UncheckedIOException(failure); }
|
||||
return new CompilerBuildGateway.CompilerBuildOutput(result.bytecodeArtifactPath(),
|
||||
compiled.analysisSnapshot().irBackend().getReservedMetadata().requiredCapabilities().asList());
|
||||
};
|
||||
compiled.analysisSnapshot().irBackend().getReservedMetadata().requiredCapabilities().asList(),admitted.issues(),admitted.context());
|
||||
}};
|
||||
var setup = new ProjectLocalStudioSetupStore(mapper);
|
||||
var project = new ProjectCatalogService(projectRoot, mapper, setup).openProject(projectRoot);
|
||||
try (var workers = Executors.newSingleThreadExecutor()) {
|
||||
var build = new StudioShipperService(compiler, packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers))
|
||||
.withAssetPreflight(new p.studio.app.assets.AssetBudgetInspection(mapper,packer.workspaceService(),ignored->new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null)))
|
||||
.prepare(project, ignored -> {}).completion().toCompletableFuture().get(30, TimeUnit.SECONDS);
|
||||
assertTrue(build.success(), build.diagnostics().toString());
|
||||
var manifest = mapper.readTree(build.manifestPath().toFile());
|
||||
@@ -219,6 +223,8 @@ class MemcardInstalledRuntimeTest {
|
||||
var refusal = assertThrows(ExecutionException.class, () -> memory.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS));
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, ((AutomationException) refusal.getCause()).failure().code());
|
||||
assertTrue(memory.alive()); assertTrue(memcard(memory).path("dirty").booleanValue());
|
||||
assertNotNull(memory.observation().nativeDetails().get("memcard"));
|
||||
assertTrue(memory.observation().recovery().stream().anyMatch(action -> action.action().equals("inspect_memcard")));
|
||||
var resetRefusal = assertThrows(AutomationException.class, () -> memory.call(TaskTools.HeadlessAction.RESET, Map.of()));
|
||||
assertEquals(AutomationFailure.Code.MEMCARD_ERROR, resetRefusal.failure().code());
|
||||
assertTrue(memory.alive()); assertTrue(memcard(memory).path("dirty").booleanValue());
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Inventory } from @zelda1:inventory;
|
||||
import { WorldFlags } from @zelda1:world;
|
||||
import { SaveStore } from @zelda1:save;
|
||||
import { Log } from @sdk:log;
|
||||
declare global tick: int=0;
|
||||
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
|
||||
[Init] fn init() -> void { Inventory.reset(); WorldFlags.reset(); }
|
||||
[Frame] fn frame() -> void {
|
||||
if tick==0 {
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e0\",\"kind\":\"suite_start\",\"payload\":{\"ordinal\":0}}");
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e1\",\"kind\":\"case_start\",\"payload\":{\"ordinal\":1},\"caseId\":\"readback\"}");
|
||||
} else if tick==1 {
|
||||
let loaded=SaveStore.load();
|
||||
if loaded && Inventory.read_slot(1)==4 && Inventory.read_slot(22)==110 && WorldFlags.room_item_taken(68) {
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e2\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":2,\"name\":\"public readback\",\"message\":\"Zelda public API\",\"expected\":true,\"actual\":true,\"passed\":true},\"caseId\":\"readback\"}"); } else { Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e2\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":2,\"name\":\"public readback\",\"message\":\"Zelda public API\",\"expected\":true,\"actual\":false,\"passed\":false},\"caseId\":\"readback\"}"); }
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e3\",\"kind\":\"case_end\",\"payload\":{\"ordinal\":3},\"caseId\":\"readback\"}");
|
||||
} else if tick==2 { Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e4\",\"kind\":\"suite_end\",\"payload\":{\"ordinal\":4,\"eventCount\":5}}"); }
|
||||
tick+=1;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Inventory } from @zelda1:inventory;
|
||||
import { WorldFlags } from @zelda1:world;
|
||||
import { SaveStore } from @zelda1:save;
|
||||
import { Log } from @sdk:log;
|
||||
import { CaveSupplyShop } from @zelda1:stages/cave_supply_shop;
|
||||
declare global tick: int=0;
|
||||
declare global started: bool=false;
|
||||
declare global reported: bool=false;
|
||||
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
|
||||
[Init] fn init() -> void {
|
||||
let values=new array<int>(40);
|
||||
values[24]=34; values[25]=255; values[37]=8; values[22]=130;
|
||||
Inventory.restore_slots(values); WorldFlags.reset(); CaveSupplyShop.enter();
|
||||
}
|
||||
[Frame] fn frame() -> void {
|
||||
SaveStore.poll(); Inventory.tick_money(tick);
|
||||
if tick==0 {
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e0\",\"kind\":\"suite_start\",\"payload\":{\"ordinal\":0}}");
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e1\",\"kind\":\"case_start\",\"payload\":{\"ordinal\":1},\"caseId\":\"purchase\"}");
|
||||
} else if tick==1 {
|
||||
let item=CaveSupplyShop.purchase(120,152);
|
||||
if item>=0 && Inventory.read_slot(1)==4 && Inventory.read_slot(39)==20 && WorldFlags.room_item_taken(68) {
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e2\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":2,\"name\":\"public purchase\",\"message\":\"Zelda public API\",\"expected\":true,\"actual\":true,\"passed\":true},\"caseId\":\"purchase\"}"); } else { Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e2\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":2,\"name\":\"public purchase\",\"message\":\"Zelda public API\",\"expected\":true,\"actual\":false,\"passed\":false},\"caseId\":\"purchase\"}"); }
|
||||
} else if tick==2 {
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e3\",\"kind\":\"case_end\",\"payload\":{\"ordinal\":3},\"caseId\":\"purchase\"}");
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e4\",\"kind\":\"case_start\",\"payload\":{\"ordinal\":4},\"caseId\":\"commit\"}");
|
||||
}
|
||||
if tick>=3 && !started && Inventory.read_slot(39)==0 { SaveStore.begin(); started=true; }
|
||||
if started && !reported && !SaveStore.busy() && SaveStore.last_state()!=1 {
|
||||
if SaveStore.last_state()==2 && !SaveStore.memory_only() && Inventory.read_slot(22)==110 {
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e5\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":5,\"name\":\"public commit\",\"message\":\"Zelda public API\",\"expected\":true,\"actual\":true,\"passed\":true},\"caseId\":\"commit\"}"); } else { Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e5\",\"kind\":\"assertion\",\"payload\":{\"ordinal\":5,\"name\":\"public commit\",\"message\":\"Zelda public API\",\"expected\":true,\"actual\":false,\"passed\":false},\"caseId\":\"commit\"}"); }
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e6\",\"kind\":\"case_end\",\"payload\":{\"ordinal\":6},\"caseId\":\"commit\"}");
|
||||
Log.info(41003,"{\"schemaVersion\":1,\"suiteId\":\"shop-save\",\"eventId\":\"e7\",\"kind\":\"suite_end\",\"payload\":{\"ordinal\":7,\"eventCount\":8}}");
|
||||
reported=true;
|
||||
}
|
||||
tick+=1;
|
||||
}
|
||||
Reference in New Issue
Block a user