#!/usr/bin/env python3 """Build the machine-readable evidence inventory; does not mutate product sources.""" import collections import datetime import hashlib import json from pathlib import Path import platform import subprocess import zipfile HERE = Path(__file__).resolve().parent ROOT = HERE.parents[3] def sha(data): return hashlib.sha256(data).hexdigest() def run(*args): # The available Python is Intel/Rosetta, while this host's CommandLineTools are arm64-only. command = ["/usr/bin/arch", "-arm64", *args] if platform.system() == "Darwin" and platform.machine() == "x86_64" else list(args) return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip() def anchor(path, needle): source = (ROOT / path).read_text() return {"path": path, "line": next(i for i, line in enumerate(source.splitlines(), 1) if needle in line), "sourceSha256": sha(source.encode())} def tree_digest(directory): files = sorted(p for p in directory.rglob("*") if p.is_file()) hashes = [(str(p.relative_to(directory)), sha(p.read_bytes())) for p in files] return {"files": len(hashes), "sha256": sha(json.dumps(hashes, separators=(",", ":")).encode())} def main(): corpus = json.loads((HERE / "cases.json").read_text())["cases"] runtime = {mode: json.loads((HERE / "reports" / mode / "runtime.json").read_text()) for mode in ("checkout", "installed")} summaries = {mode: json.loads((HERE / "reports" / mode / "summary.json").read_text()) for mode in runtime} result = {"schemaVersion": 1, "discussion": "DSC-0111", "agenda": "AGD-0113", "cases": []} for case in corpus: item = {k: case[k] for k in ("id", "family", "description", "control", "expectedCompile", "expectedRuntime", "sourceSha256")} observations = [] for mode in runtime: for observation in [i for i in summaries[mode]["cases"] if i["id"] == case["id"]]: report = json.loads((HERE / observation["report"]).read_text()) assert report["sourceSha256"] == case["sourceSha256"], case["id"] row = {"mode": mode, **observation} row["diagnostics"] = [] for phase in report["phases"]: for diagnostic in phase["diagnostics"]: diag = {k: diagnostic.get(k) for k in ("code", "phase", "start", "end", "functionIndex", "pc", "message")} if diagnostic.get("file"): diag["file"] = str(Path(diagnostic["file"]).resolve().relative_to(Path(report["projectRoot"]).resolve())) row["diagnostics"].append(diag) observations.append(row) assert len(observations) == 6, (case["id"], observations) assert len({o["status"] for o in observations if not o["public"]}) == 1 assert all(o["status"] == "compiled" for o in observations if o["public"]) == all(o["status"] == "compiled" for o in observations if not o["public"]) status = next(o["status"] for o in observations if not o["public"]) if case["expectedCompile"] == "rejected": assert status == "analysis_failed" classification = "expected_rejection" elif status != "compiled": classification = "reproduced_failure" elif case["expectedRuntime"] == "fault": classification = "harness_control" else: classification = "compiled_and_executed" item["classification"] = classification item["observations"] = observations item["executions"] = [{"mode": mode, **{k: e[k] for k in ("optimization", "observedRuntime", "matchesExpectation", "bytecodeSha256")}} for mode in runtime for e in runtime[mode]["cases"] if e["id"] == case["id"]] if status == "compiled": assert len(item["executions"]) == 4 and all(e["matchesExpectation"] for e in item["executions"]), case["id"] result["cases"].append(item) prefix = "prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/" lowerer = prefix + "p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java" result["findings"] = [ {"id": "PBS-EXPRESSION-CONTEXT", "owner": "compiler/pbs", "status": "reproduced_and_localized", "cases": ["F1-direct", "F1-two-calls", "F1-service-this"], "controls": ["F1-local", "F1-service-local", "F1-condition"], "mechanism": "Returned boolean context is retained while lowering binary operands; structured method candidate filtering compares the int return against the enclosing bool expected type. Direct if condition and local materialization pass.", "code": [anchor(lowerer, "case PbsAst.BinaryExpr binaryExpr ->"), anchor(lowerer, "private void lowerExpected("), anchor(lowerer, "private boolean returnMatches(")]}, {"id": "PBS-MODULE-PEER-SURFACE", "owner": "compiler/pbs", "status": "reproduced_and_localized", "cases": ["F3-function", "F3-global", "F3-service"], "controls": ["F3-single-file", "F3-global-local", "F3-service-local", "F3-file-private"], "mechanism": "Sibling collection contributes type/generic declarations but not ordinary peer function/global surfaces; peer service type availability does not provide the corresponding callable binding. Valid mod declarations fail when moved to a second file.", "code": [anchor(prefix + "p/studio/compiler/services/PbsImportedSemanticContextService.java", "for (var sibling :")]}, {"id": "PBS-NOMINAL-DEPENDENCY", "owner": "compiler/pbs", "status": "reproduced_with_source_hypothesis", "cases": ["F4-same-dependency", "F4-same-direct"], "controls": ["F4-distinct", "F4-same-no-dependency", "F4-rename-a", "F4-public-aliases"], "mechanismHypothesis": "Flat simple-name runtime type/signature indexes combine local and dependency declarations; private homonymous owner context can be replaced, leading to exact receiver signature mismatch. Differential tests establish the dependency/name interaction; exact correction and full scope are not yet verified.", "code": [anchor(prefix + "p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java", "structs.put(s.name(), s);"), anchor(prefix + "p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java", "boolean matches =")]} ] result["notReproduced"] = [ {"report": "Historical MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT with complex expressions/factories", "scope": "Four nested-call variants compile and execute; no such verifier error occurs in this reduced corpus. This does not establish that all historical shapes are fixed."}, {"report": "Historical Unsupported PBS runtime type: Scene", "scope": "Scene and ShopVisit construction/cross-module parameters, Scene alias and positional construction compile and execute. Exact historical project state remains unqualified."} ] result["handoffs"] = [ {"agenda": "AGD-0114", "finding": "Analysis diagnostics are followed by builder pipeline completed successfully in the production facade logs. No historical backend RET stack mismatch has been reproduced here.", "evidence": "reports/checkout/F1-direct-optimized-public.json"}, {"agenda": "AGD-0115", "finding": "The analysis entrypoint returns code/span; compile rejects with generic BuildException and diagnostics remain in logs. Preserve the structured diagnostic through consumer adapters. No live LSP/MCP query was exercised in this corpus.", "evidence": "reports/checkout/F1-direct-optimized.json"} ] result["counts"] = {"cases": len(corpus), "classifications": dict(collections.Counter(c["classification"] for c in result["cases"])), "finalCompileObservations": sum(len(c["observations"]) for c in result["cases"]), "finalRuntimeExecutions": sum(len(c["executions"]) for c in result["cases"])} result["limitations"] = [ "Research fixtures only; no product implementation or correction was made.", "The nonoptimized path omits OptimizeIRVMPipelineStage and emits the original IRVM. It is a research variant, not a claimed public compiler option.", "Public BuilderPipelineService.compile was checked for the default optimized pipeline; all cases also ran through the corresponding production stages.", "Each case compiled in a separate JVM. Installed mode used only distribution JARs and a scratch working directory outside the repository.", "Execution used the existing sibling debug headless binary, identified by hash. This is not qualification of an installed runtime distribution or live Studio UI/MCP.", "Final counts describe the completed matrix, excluding earlier smoke/retry attempts.", "An initial harness handshake incorrectly requested memcard with protocol 1.0. The attempt is preserved in reports/checkout/runtime-initial-handshake.json; the corrected harness negotiates supported version and only needed capabilities.", "Absolute scratch paths in detailed reports are observational; cases.json contains all source inputs needed to rematerialize them." ] (HERE / "inventory.json").write_text(json.dumps(result, indent=2) + "\n") modules = ["prometeu-infra", "prometeu-animation", "prometeu-compiler/prometeu-compiler-core", "prometeu-compiler/prometeu-frontend-api", "prometeu-compiler/frontends/prometeu-frontend-pbs", "prometeu-compiler/prometeu-frontend-registry", "prometeu-compiler/prometeu-deps", "prometeu-compiler/prometeu-build-pipeline"] install = ROOT / "prometeu-app/build/install/prometeu-app" provenance = {"schemaVersion": 1, "capturedAtUtc": datetime.datetime.now(datetime.timezone.utc).isoformat(), "studioRevision": run("git", "rev-parse", "HEAD"), "studioWorktreeStatus": run("git", "status", "--short").splitlines(), "platform": platform.platform(), "machine": platform.machine(), "java": subprocess.run([str(install / "runtime/bin/java"), "-version"], capture_output=True, text=True, check=True).stderr.strip(), "modules": [], "runtimeExecutables": [{k: runtime[m][k] for k in ("binary", "binarySha256")} for m in runtime], "scope": "Runtime binaries were read/executed only; all cartridge/media-free fixture writes belong to scratch directories."} for module in modules: directory = ROOT / module jar = install / "lib" / (directory.name + ".jar") item = {"path": module, "sources": tree_digest(directory / "src/main"), "classes": tree_digest(directory / "build/classes/java/main"), "installedJarSha256": sha(jar.read_bytes())} matches = 0 differences = [] with zipfile.ZipFile(jar) as archive: for path in sorted((directory / "build/classes/java/main").rglob("*.class")): relative = str(path.relative_to(directory / "build/classes/java/main")) if relative in archive.namelist() and sha(path.read_bytes()) == sha(archive.read(relative)): matches += 1 else: differences.append(relative) item["installedClassComparison"] = {"matching": matches, "differentOrMissing": differences} provenance["modules"].append(item) (HERE / "provenance.json").write_text(json.dumps(provenance, indent=2) + "\n") checksums = [] for path in sorted(HERE.rglob("*")): if path.is_file() and path.name != "SHA256SUMS" and "__pycache__" not in path.parts: checksums.append(sha(path.read_bytes()) + " " + str(path.relative_to(HERE))) (HERE / "SHA256SUMS").write_text("\n".join(checksums) + "\n") print(json.dumps(result["counts"], indent=2)) print("Installed class differences:", sum(len(m["installedClassComparison"]["differentOrMissing"]) for m in provenance["modules"])) if __name__ == "__main__": main()