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; Path root = Files.createDirectory(Path.of("example")).toRealPath(); var docs = provider.documentation().orElseThrow().references(1, p.studio.AppMode.Game); 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"); 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"); 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()); System.out.println("Installed List/Cursor execution fixture generated"); 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 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}; } }