package p.studio.app.compiler; import com.fasterxml.jackson.databind.ObjectMapper; import p.studio.api.automation.ProjectKnowledge; import p.studio.compiler.FrontendRegistryService; import p.studio.compiler.messages.BuilderPipelineConfig; import p.studio.compiler.models.BuilderPipelineContext; import p.studio.compiler.workspaces.BuilderPipelineService; import p.studio.core.project.*; import p.studio.utilities.logs.LogAggregator; import java.nio.file.Files; import java.nio.file.Path; /** Separate JVM gate: product classes/resources must resolve exclusively from installDist JARs. */ public final class InstalledKnowledgeProbe { public static void main(String[] arguments) throws Exception { var provider = FrontendRegistryService.require("pbs"); check(provider.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "Frontend must come from installed JAR"); check(CompilerProjectKnowledge.class.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith(".jar"), "App must come from installed JAR"); check(!Files.exists(Path.of("settings.gradle.kts")) && !Files.exists(Path.of("docs")), "No repository in working directory"); 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"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/generics.pbs")), "Missing installed generic struct/function example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-list-and-cursor.md")), "Missing installed List/Cursor specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/collections.pbs")), "Missing installed List/Cursor example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-linked-and-cursor.md")), "Missing installed Linked specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/linked.pbs")), "Missing installed Linked example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-set-and-identity.md")), "Missing installed Set/Identity specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/sets.pbs")), "Missing installed Set example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-map-and-keyval.md")), "Missing installed Map/Keyval specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/maps.pbs")), "Missing installed Map/Keyval example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-stack-and-queue.md")), "Missing installed Stack/Queue specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/stack-queue.pbs")), "Missing installed Stack/Queue example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/lifecycle.pbs")), "Missing installed lifecycle example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:LIFECYCLE.md")), "Missing installed lifecycle documentation"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/hashing.pbs")), "Missing installed hashing example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:sdk:game:1:sdk/hash/main.pbs")), "Missing installed hash SDK"); for (var reference : docs) { if (reference.id().startsWith("pbs:example:game:1:")) { Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length())); Files.createDirectories(file.getParent()); Files.writeString(file, reference.text()); } } var mapper = new ObjectMapper(); var access = new ProjectAccessRegistry(); var registration = access.register(root, () -> { throw new AssertionError("References require no grant"); }, () -> true); var catalog = new ProjectCatalogService(root, mapper, new ProjectLocalStudioSetupStore(mapper)); var knowledge = new CompilerProjectKnowledge(access, catalog, mapper); var context = knowledge.context(root); for (var kind : java.util.List.of(ProjectKnowledge.ReferenceKind.QUICKSTART, ProjectKnowledge.ReferenceKind.SYNTAX, ProjectKnowledge.ReferenceKind.SEMANTICS, ProjectKnowledge.ReferenceKind.EXAMPLE, ProjectKnowledge.ReferenceKind.SDK)) check(context.references().stream().anyMatch(ref -> ref.kind() == kind), "Missing " + kind); for (var reference : docs) { var actual = new StringBuilder(); int offset = 0; while (true) { var page = knowledge.readReference(root, reference.id(), offset, 997); actual.append(page.text()); if (page.nextOffset() == null) break; offset = page.nextOffset(); } check(actual.toString().equals(reference.text()), "Incorrect installed reference: " + reference.id()); } var result = BuilderPipelineService.INSTANCE.compile( BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), LogAggregator.stdout()); check(result.diagnostics().stream().noneMatch(issue -> issue.isError()), "Example must compile without errors"); check(result.bytecodeBytes().length > 0, "Example must produce bytecode"); for (var role : java.util.List.of(p.studio.compiler.models.registry.IRRegistry.Role.BEFORE_PAUSE, p.studio.compiler.models.registry.IRRegistry.Role.BEFORE_RESUME)) { 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")); Files.writeString(listRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;"); Files.writeString(listRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/collections.pbs"))+"\n"+""" [Frame] fn frame() -> void { if collectionsExample()!=42 {let failure=1/0;} } """); var listResult=BuilderPipelineService.INSTANCE.compile( BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,listRoot.toString())),LogAggregator.stdout()); check(listResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed List/Cursor example must compile"); Path fixtures=Path.of(System.getProperty("pbs.registryConformanceDirectory")); Files.createDirectories(fixtures);Files.write(fixtures.resolve("pbs-list-installed.pbx"),listResult.bytecodeBytes()); check(docs.stream().anyMatch(r -> r.id().equals("pbs:sdk:game:1:sdk/mem/main.pbs")), "Missing installed mem SDK"); var memcardResult = BuilderPipelineService.INSTANCE.compile( BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.resolve("memcard").toString())), LogAggregator.stdout()); check(memcardResult.diagnostics().stream().noneMatch(issue -> issue.isError()), "Installed opt-in memcard project must compile"); check(memcardResult.bytecodeModule().functions().stream().filter(f -> f.metadata().role() == p.studio.compiler.models.registry.IRRegistry.Role.MEMCARD_BOOT).count() == 1, "Installed MemcardBoot role"); check(memcardResult.bytecodeModule().syscalls().stream().anyMatch(s -> s.module().equals("mem") && s.name().equals("slot_stat") && s.retSlots() == 7), "Installed memcard ABI must preserve all seven stat results"); Files.write(fixtures.resolve("pbs-memcard-installed.pbx"), memcardResult.bytecodeBytes()); System.out.println("Installed memcard execution fixture generated"); System.out.println("Installed List/Cursor execution fixture generated"); Path linkedRoot=Files.createDirectory(Path.of("linked-example")).toRealPath(); Files.createDirectories(linkedRoot.resolve("src")); Files.copy(root.resolve("prometeu.json"),linkedRoot.resolve("prometeu.json")); Files.writeString(linkedRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;"); Files.writeString(linkedRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/linked.pbs"))+"\n"+""" [Frame] fn frame() -> void { if linkedExample()!=42 {let failure=1/0;} } """); var linkedResult=BuilderPipelineService.INSTANCE.compile( BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,linkedRoot.toString())),LogAggregator.stdout()); check(linkedResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed Linked example must compile"); Files.write(fixtures.resolve("pbs-linked-installed.pbx"),linkedResult.bytecodeBytes()); System.out.println("Installed Linked execution fixture generated"); for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs","animation","animation.pbs").entrySet()) { Path exampleRoot=Files.createDirectory(Path.of(example.getKey()+"-example")).toRealPath(); Files.createDirectories(exampleRoot.resolve("src")); Files.copy(root.resolve("prometeu.json"),exampleRoot.resolve("prometeu.json")); Files.writeString(exampleRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;"); String function=switch(example.getKey()){case "animation"->"animationExample";case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";}; Files.writeString(exampleRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/"+example.getValue())) +(example.getKey().equals("animation")?"\n[Frame] fn frame()->void { animationExample(); }":"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}")); var exampleResult=BuilderPipelineService.INSTANCE.compile( BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,exampleRoot.toString())),LogAggregator.stdout()); check(exampleResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed "+example.getKey()+" example must compile: "+exampleResult.diagnostics()); Files.write(fixtures.resolve("pbs-"+example.getKey()+"-installed.pbx"),exampleResult.bytecodeBytes()); System.out.println("Installed "+example.getKey()+" execution fixture generated"); } ProductionContractsInstalledProbe.verify(root, fixtures.resolve("production-contracts")); p.studio.app.animation.AnimationInstalledProbe.verify(Files.createDirectory(Path.of("animation-authored")).toRealPath(),fixtures); p.studio.app.animation.AnimationInstalledProbe.verify(Files.createDirectory(Path.of("animation-hyphenated")).toRealPath(),fixtures,"zelda-1"); verifyExternalSources(provider.getClass().getClassLoader()); registration.unsubscribe(); System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled"); } private static void check(boolean condition, String message) { if (!condition) throw new AssertionError(message); } private static void verifyIsolatedTargets(Path root) throws Exception { var originals = new java.util.HashMap(); 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 docs) throws Exception { var resource = loader.getResource("pbs-knowledge/index.json"); check(resource != null && resource.getProtocol().equals("jar"), "Reference index must come from installed JAR"); var entries = new java.util.HashMap(); try (var stream = resource.openStream()) { new ObjectMapper().readTree(stream).get("references") .forEach(entry -> entries.put(entry.get("id").asText(), entry)); } var aliases = docs.stream().filter(ref -> ref.id().startsWith("pbs:spec:") && ref.id().endsWith(".md")).toList(); check(aliases.size() == 12, "All 12 published filename IDs must remain installed"); for (var alias : aliases) { var old = entries.get(alias.id()); var chapter = docs.stream().filter(ref -> ref.id().matches("pbs:spec:[0-9]+") && entries.get(ref.id()).get("resource").equals(old.get("resource"))).findFirst().orElseThrow(); check(chapter.text().equals(alias.text()), "Installed alias text mismatch: " + alias.id()); check(entries.get(chapter.id()).get("sha256").equals(old.get("sha256")), "Installed alias hash mismatch: " + alias.id()); check(loader.getResource(old.get("resource").asText()).getProtocol().equals("jar"), "Alias must use a canonical JAR resource"); } System.out.println("Installed specification aliases verified: 12 canonical resources"); } private static void verifyRuntimeCatalogs(ClassLoader loader) throws Exception { var names = java.util.List.of("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv", "runtime-catalog.properties"); var compiler = new java.util.HashMap(); for (var name : names) { for (var owner : java.util.List.of("compiler", "pbs-sdk")) { var resource = loader.getResource("runtime-catalog/" + owner + "/" + name); check(resource != null && resource.getProtocol().equals("jar"), "Missing installed catalog: " + owner + "/" + name); try (var stream = resource.openStream()) { var bytes = stream.readAllBytes(); if (owner.equals("compiler")) compiler.put(name, bytes); else check(java.util.Arrays.equals(compiler.get(name), bytes), "Compiler/SDK contract mismatch: " + name); } } } var properties = new java.util.Properties(); properties.load(new java.io.ByteArrayInputStream(compiler.get("runtime-catalog.properties"))); check(properties.getProperty("runtime.revision").matches("[0-9a-f]{40}"), "Missing target revision"); for (var name : names.subList(0, 2)) { var digest = java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(compiler.get(name))); check(digest.equals(properties.getProperty(name + ".sha256")), "Packaged catalog hash mismatch: " + name); } System.out.println("Installed compiler/SDK catalog identity verified: " + properties.getProperty("runtime.revision")); } private static void verifyExternalSources(ClassLoader loader) throws Exception { var resource = loader.getResource("game/stdlib/1/sdk/gfx/main.pbs"); check(resource != null && resource.getProtocol().equals("jar"), "SDK must be read from a JAR URL"); check(p.studio.lsp.services.compiler.CompilerLanguageServiceBridge.class.getProtectionDomain() .getCodeSource().getLocation().getPath().endsWith(".jar"), "LSP bridge must come from installed JAR"); Path root = Files.createDirectory(Path.of("external-sources")).toRealPath(); Files.createDirectories(root.resolve("src")); Files.writeString(root.resolve("prometeu.json"), """ {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} """); String source = "import { Gfx } from @sdk:gfx;\nfn main() -> void { Gfx.clear(0); }\n"; Path file = Files.writeString(root.resolve("src/main.pbs"), source); Files.writeString(root.resolve("src/mod.barrel"), "pub fn main() -> void;\n"); var context = new p.studio.lsp.messages.LspProjectContext("installed", "pbs", root); var bridge = new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(); try (var registry = new p.studio.lsp.services.compiler.ExternalSourceRegistry()) { String consumer = registry.connect(null, false); int[] sdkUse = position(source, "Gfx.clear", "Gfx.".length()); var targets = bridge.navigation(context, file.toUri().toString(), source, sdkUse[0], sdkUse[1], registry, consumer).locations(); check(targets.size() == 1, "Packaged SDK definition must resolve"); String uri = targets.getFirst().uri(); check(uri.startsWith("prometeu-source:"), "SDK must use a virtual URI"); var content = registry.read(consumer, uri); check(content.descriptor().readOnly() && content.descriptor().origin().equals("bundled"), "Bundled SDK must be read-only"); try (var stream = resource.openStream()) { check(content.text().equals(new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)), "SDK text must exactly match JAR bytes"); } int[] hostUse = position(content.text(), "LowGfx.clear", "LowGfx.".length()); check(bridge.externalHover(context, uri, hostUse[0], hostUse[1], registry, consumer).markdown().contains("clear"), "SDK hover must work"); var host = bridge.navigation(context, uri, null, hostUse[0], hostUse[1], registry, consumer).locations().getFirst(); check(registry.read(consumer, host.uri()).text().split("\n")[host.startLine()].contains("clear"), "SDK to host definition range must match"); check(!bridge.externalSemanticTokens(context, uri, registry, consumer).tokens().isEmpty(), "SDK semantic highlighting must work"); int[] colorUse = position(content.text(), "color: Color", 7); var core = bridge.navigation(context, uri, null, colorUse[0], colorUse[1], registry, consumer).locations().getFirst(); var coreContent = registry.read(consumer, core.uri()); check(coreContent.descriptor().readOnly() && coreContent.descriptor().name().replace('\\', '/').contains("core/color"), "SDK to core definition must resolve"); var coreResource = loader.getResource("game/stdlib/1/core/color/main.pbs"); check(coreResource != null && coreResource.getProtocol().equals("jar"), "Core must be read from a JAR URL"); try (var stream = coreResource.openStream()) { check(coreContent.text().equals(new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)), "Core text must exactly match JAR bytes"); } check(coreContent.text().split("\n")[core.startLine()].contains("Color"), "Core definition range must match"); registry.disconnect(consumer); registry.connect(consumer, false); check(registry.revalidate(consumer, uri, path -> bridge.currentSource(context, path)).text().equals(content.text()), "Bundled source must revalidate after reconnect"); } try (var files = Files.walk(root)) { check(files.filter(Files::isRegularFile).map(root::relativize).map(Path::toString).collect(java.util.stream.Collectors.toSet()) .equals(java.util.Set.of("prometeu.json", "src/main.pbs", "src/mod.barrel")), "Navigation must not extract bundled sources into the project"); } System.out.println("Packaged external sources verified: JAR bytes, SDK/host/core navigation, hover, tokens, read-only, reconnect, no extraction"); } private static int[] position(String text, String needle, int offset) { int index = text.indexOf(needle); check(index >= 0, "Missing source fragment: " + needle); String prefix = text.substring(0, index + offset); return new int[] {(int) prefix.chars().filter(c -> c == '\n').count(), prefix.length() - prefix.lastIndexOf('\n') - 1}; } }