qualify-compat.py

cdk-rsx/tools/qualify-compat.py

qualify-compat.py728 lines← SDK documentation
1#!/usr/bin/env python32"""Qualify exact SDK implementation aliases using frozen builds and reviewed gates.34This coordinator binds evidence to exact inputs/artifacts; trusted runners and5an explicit owner review establish its meaning. It cannot infer Rust semantic6equivalence from a passing command. No aliases are installed by plan or run.78Use preflight --baseline OLD.manifest.json --candidate NEW.manifest.json to9compare effective compiler policies for a KEEP rehearsal using existing builds.1011Workflow: plan --baseline OLD.manifest.json --candidate RAW.manifest.json12--output PLAN; run --plan PLAN/plan.json --suite SUITE.json --output RUN;13approve --qualification RUN/qualification.json --review REVIEW.json14--registry approved.json. Output directories must be fresh. verify accepts15--qualification (full local evidence), --plan, or --registry (portable approval).1617Suite format cdk-rsx-compat-suite-v1 has inputs (pinned files including runner,18helper/import closure and host dependency locks), server:{path,bytes,sha256},19candidate_build:[argv], candidate_manifest:path, artifacts:{layout,meaning,20unqualified,trap} manifest paths, and nonempty native/ic gate arrays. Each gate21has name, contract (reviewed meaning), argv; native also has role baseline,22candidate or pair, covering both versions. Commands run without a shell.23Placeholders: {aliases}, {output}, {baseline_manifest}, {candidate_manifest},24{baseline_wasm}, {candidate_wasm}, {result}; candidate fields become available25after the canonical candidate build. Relative paths resolve from suite.parent;26optional cwd selects command working directory. Native commands consume their27role's manifest; IC commands consume both Wasm paths and a fresh result path.2829IC result format cdk-rsx-compat-lifecycle-v1 contains target, baseline_sha256,30candidate_sha256, server record, artifacts (six exact baseline/candidate/layout/31meaning/unqualified/trap file records), the eight CHECKS booleans, and detailed32stages. First stages old_state_populated/forward_keep/fresh_writes/reverse_keep33include sha256 for baseline/candidate/candidate/baseline, in that order.34Checks: old_state_populated, forward_keep, fresh_writes, reverse_keep,35trap_rollback, layout_rejected, meaning_rejected, unqualified_rejected.36Review format cdk-rsx-compat-review-v1 is emitted as a template by plan: fill37reviewer, common_class_invariant:true, and every scope's unchanged read/write38interpretation statements. Gate results do not supply that semantic review.39"""4041import argparse42from contextlib import contextmanager43import hashlib44import importlib.util45import json46import os47from pathlib import Path48import re49import shlex50import shutil51import signal52import subprocess53import sys5455from compatibility import (canonical_bytes, eligible_scope, load_document,56                           load_registry, merge_aliases, sha256_file,57                           validate_aliases, validate_inventory)5859TOOLS = Path(__file__).resolve().parent60CHECKS = ("old_state_populated", "forward_keep", "fresh_writes", "reverse_keep",61          "trap_rollback", "layout_rejected", "meaning_rejected", "unqualified_rejected")62ROLES = ("baseline", "candidate", "layout", "meaning", "unqualified", "trap")63GEOMETRY = ("profile", "memory64", "pointer_width", "page_size", "address_limit",64            "platform_format", "stack_bytes", "hot_control_base", "hot_control_bytes",65            "static_data_base", "static_limit", "control_base", "bootstrap_address",66            "initial_memory_bytes", "typed_root")67EMPTY_ALIASES = {"format": "cdk-rsx-compat-aliases-v1", "entries": []}68HEX = re.compile(r"[0-9a-f]{64}\Z")697071def require(condition, message):72    if not condition:73        raise ValueError(message)747576def document(path, kind):77    value = load_document(Path(path))78    require(isinstance(value, dict) and value.get("format") == kind,79            f"expected {kind}: {path}")80    return value818283def record(path):84    path = Path(path).resolve(strict=True)85    require(path.is_file(), f"not a file: {path}")86    return {"path": str(path), "bytes": path.stat().st_size, "sha256": sha256_file(path)}878889def checked(row, base=None):90    require(isinstance(row, dict) and isinstance(row.get("path"), str)91            and HEX.fullmatch(row.get("sha256", ""))92            and isinstance(row.get("bytes"), int) and not isinstance(row["bytes"], bool),93            "invalid pinned file record")94    path = Path(row["path"])95    if not path.is_absolute():96        require(base is not None, f"relative evidence path without base: {path}")97        path = Path(base) / path98    actual = record(path)99    require(actual["sha256"] == row["sha256"] and actual["bytes"] == row["bytes"],100            f"pinned input changed: {path}")101    return actual102103104def write_new(path, value):105    path = Path(path)106    path.parent.mkdir(parents=True, exist_ok=True)107    with path.open("xb") as output:108        output.write(canonical_bytes(value))109    return record(path)110111112def fresh_output(path):113    path = Path(path).resolve()114    path.mkdir(parents=True, exist_ok=False)115    return path116117118def completion(path, outputs):119    marker = path.with_name(path.name.removesuffix(".manifest.json") + ".SHA256SUMS")120    expected = {Path(row["path"]).name: row["sha256"] for row in outputs}121    expected[path.name] = sha256_file(path)122    actual = {}123    for line in marker.read_text().splitlines():124        require(len(line) > 66 and line[64:66] == "  " and HEX.fullmatch(line[:64]),125                f"invalid completion marker: {marker}")126        name = line[66:]127        require(Path(name).name == name and name not in actual,128                f"unsafe or duplicate completion entry: {name}")129        actual[name] = line[:64]130    require(actual == expected, f"incomplete or stale artifact publication: {marker}")131    return record(marker)132133134def artifact_manifest(path, *, candidate=False, include_rustflags=False):135    path = Path(path).resolve(strict=True)136    require(path.name.endswith(".manifest.json"), "expected canonical *.manifest.json")137    value = document(path, "cdk-rsx-typed-root-artifacts-v1")138    build = value.get("canonicalBuild", {})139    require(value.get("implementation") == "cdk-rsx"140            and value.get("sourceUnchangedDuringBuild") is True141            and isinstance(build, dict)142            and build.get("source_unchanged_during_build") is True143            and build.get("runtime") == "typed-root", "not a complete canonical typed-root build")144    outputs = [checked(row) for row in value.get("outputs", [])]145    require(outputs and len({row["path"] for row in outputs}) == len(outputs),146            "missing or duplicate artifact outputs")147    require(all(Path(row["path"]).parent == path.parent for row in outputs),148            "artifact outputs must share their manifest directory")149    published = completion(path, outputs)150    by_name = {Path(row["path"]).name: row for row in outputs}151    stem = path.name.removesuffix(".manifest.json")152153    def output(suffix):154        name = f"{stem}.{suffix}"155        require(name in by_name, f"missing completed artifact output: {name}")156        return by_name[name]157158    wasm, raw = output("wasm"), output("raw.wasm")159    require(value.get("wasmSha256") == wasm["sha256"]160            and build.get("raw_wasm_sha256") == raw["sha256"], "Wasm role/hash mismatch")161    compat = build.get("compatibility", {})162    require(isinstance(compat, dict) and compat.get("status") in ("approved", "candidate"),163            "missing build compatibility provenance")164    require(candidate or compat["status"] == "approved", f"build uses unapproved candidate identities: {path}")165    aliases = validate_aliases(compat.get("aliases"))166    require(compat.get("aliases_sha256") == hashlib.sha256(canonical_bytes(aliases)).hexdigest(),167            "build alias payload hash mismatch")168    target = build.get("target")169    require(target in ("wasm32-unknown-unknown", "wasm64-unknown-unknown"), "unsupported target")170    context = compat.get("context")171    require(isinstance(context, str) and HEX.fullmatch(context), "missing exact build context")172    inventories = [validate_inventory(load_document(output(suffix)["path"]), aliases,173                                      context=context, target=target)174                   for suffix in ("raw.policies.json", "policies.json")]175    require(inventories[0] == inventories[1], "raw/prepared policy inventories differ")176    memory = load_document(output("memory.json")["path"])177    require(all(key in memory for key in GEOMETRY), "missing target geometry facts")178    sources = value.get("sources")179    require(isinstance(sources, list) and sources and all(isinstance(row, dict) for row in sources),180            "missing frozen source closure")181    require(len({row.get("path") for row in sources}) == len(sources), "duplicate source inputs")182    configuration = {"package": value.get("package"), "library": build.get("library"),183                     "target": target, "features": sorted(value.get("features", [])),184                     "geometry": {key: memory[key] for key in GEOMETRY}}185    require(configuration["package"] == build.get("package")186            and configuration["features"] == sorted(build.get("features", [])),187            "package/features disagree with build receipt")188    receipt = {"manifest": record(path), "completion": published, "wasm": wasm, "raw_wasm": raw,189               "configuration": configuration, "policies": inventories[0], "aliases": aliases,190               "context": context, "sources": sources, "compatibility_status": compat["status"]}191    if include_rustflags:192        flags = build.get("rustflags", [])193        require(isinstance(flags, list) and all(isinstance(flag, str) for flag in flags),194                f"invalid recorded Rust flags: {path}")195        receipt["rustflags"] = flags196    return receipt197198199def by_scope(inventory):200    rows = inventory["entries"]201    result = {row["scope"]: row for row in rows}202    require(len(rows) == len(result), "one exact policy per scope is required")203    require(all(eligible_scope(scope) for scope in result), "ineligible SDK policy scope")204    return result205206207def preflight(baseline_path, candidate_path):208    result, remaps = {}, {}209    for role, path in (("baseline", baseline_path), ("candidate", candidate_path)):210        artifact = artifact_manifest(path, include_rustflags=True)211        scope = f"compiler/{artifact['configuration']['target']}"212        policy = by_scope(artifact["policies"])[scope]213        result[role] = {"manifest": artifact["manifest"]["path"],214                        "wasm_sha256": artifact["wasm"]["sha256"],215                        "compiler": {key: policy[key] for key in ("scope", "identity", "raw")}}216        remaps[role] = [flag for flag in artifact["rustflags"] if flag.startswith("--remap-path-prefix=")]217218    baseline, candidate = result["baseline"]["compiler"], result["candidate"]["compiler"]219    if baseline["scope"] != candidate["scope"]:220        result.update(status="target-mismatch", next_check="Build the candidate for the installed Wasm target.")221    elif baseline["identity"] != candidate["identity"]:222        result.update(status="compiler-policy-mismatch", next_check=(223            "Compare recorded path remaps, Rust flags, pinned toolchains and SDK dependency closures. "224            "For a path-only change, rebuild the candidate at the original build paths."225        ))226    else:227        result.update(status="compiler-policy-match", next_check=(228            "If the root changed, check that the candidate declares the installed root as a predecessor. "229            "Rehearse KEEP with populated state."230        ))231    if remaps["baseline"] != remaps["candidate"]:232        result["path_remaps"] = remaps233    return result234235236def plan(baseline_path, candidate_path, output_path):237    baseline = artifact_manifest(baseline_path)238    candidate = artifact_manifest(candidate_path)239    require(baseline["configuration"] == candidate["configuration"],240            "package, target, features or persisted geometry changed")241    old, new = by_scope(baseline["policies"]), by_scope(candidate["policies"])242    require(old.keys() == new.keys(), "policy scopes changed; unknown scopes cannot be aliased")243    changed = []244    for scope, row in sorted(new.items()):245        if row["identity"] != old[scope]["identity"]:246            require(row["identity"] == row["raw"], "cannot reinterpret an already approved identity")247            changed.append(dict(row, identity=old[scope]["identity"]))248    require(changed, "no new SDK policy aliases require qualification")249    aliases = merge_aliases(candidate["aliases"], {"format": EMPTY_ALIASES["format"], "entries": changed})250    output = fresh_output(output_path)251    alias_record = write_new(output / "aliases.json", aliases)252    review = {"format": "cdk-rsx-compat-review-v1", "reviewer": "", "common_class_invariant": False,253              "scopes": [dict(row, unchanged_read_interpretation="", unchanged_write_interpretation="")254                         for row in changed]}255    write_new(output / "review-template.json", review)256    return write_new(output / "plan.json", {257        "format": "cdk-rsx-compat-plan-v1", "baseline": baseline, "candidate": candidate,258        "aliases": alias_record, "changes": changed})259260261def load_plan(path):262    value = document(path, "cdk-rsx-compat-plan-v1")263    aliases = validate_aliases(load_document(checked(value["aliases"])["path"]))264    for key in ("baseline", "candidate"):265        saved = value[key]266        checked(saved["manifest"])267        require(artifact_manifest(saved["manifest"]["path"]) == saved, f"changed planned {key} build")268    old, new = by_scope(value["baseline"]["policies"]), by_scope(value["candidate"]["policies"])269    require(old.keys() == new.keys()270            and value["baseline"]["configuration"] == value["candidate"]["configuration"],271            "plan changed scopes or configuration")272    expected = [dict(row, identity=old[scope]["identity"]) for scope, row in sorted(new.items())273                if row["identity"] != old[scope]["identity"]]274    require(value["changes"] == expected and expected, "plan's scoped policy mapping changed")275    require(aliases == merge_aliases(value["candidate"]["aliases"],276                                    {"format": EMPTY_ALIASES["format"], "entries": expected}),277            "plan alias payload is not exact")278    return value279280281def candidate_matches_plan(candidate, planned):282    require(candidate["compatibility_status"] == "candidate", "rebuilt artifact must be provisional")283    require(candidate["configuration"] == planned["candidate"]["configuration"], "candidate configuration changed")284    source_rows = {row["path"]: row for row in planned["candidate"]["sources"]}285    source_rows[planned["aliases"]["path"]] = planned["aliases"]286    require({row["path"]: row for row in candidate["sources"]} == source_rows,287            "candidate source closure differs from plan plus exact staged aliases")288    old = by_scope(planned["baseline"]["policies"])289    raw = by_scope(planned["candidate"]["policies"])290    built = by_scope(candidate["policies"])291    require(old.keys() == raw.keys() == built.keys(), "rebuilt policy scopes changed")292    require(candidate["aliases"] == validate_aliases(load_document(planned["aliases"]["path"])),293            "candidate did not compile the exact plan alias payload")294    for scope, row in built.items():295        require((row["raw"], row["context"]) == (raw[scope]["raw"], raw[scope]["context"])296                and row["identity"] == old[scope]["identity"], f"unqualified rebuilt policy: {scope}")297    require(candidate["wasm"]["sha256"] != planned["baseline"]["wasm"]["sha256"],298            "qualification must use distinct old/new executables")299300301def companion_matches(role, companion, candidate, planned):302    require(companion["configuration"] == planned["baseline"]["configuration"],303            f"{role} fixture changed package/target/features/geometry")304    expected = planned["candidate"]["policies"] if role == "unqualified" else candidate["policies"]305    require(companion["policies"] == expected,306            f"{role} probe must preserve its declared SDK policy inventory")307308309def pinned_inputs(items, base):310    require(isinstance(items, list) and items, "suite needs pinned source/runner/helper inputs")311    rows = []312    for item in items:313        if isinstance(item, str):314            rows.append(record(Path(base) / item))315        else:316            rows.append(checked(item, base))317    require(len({row["path"] for row in rows}) == len(rows), "duplicate suite input")318    return rows319320321def expand(argv, substitutions):322    require(isinstance(argv, list) and argv and all(isinstance(arg, str) and arg for arg in argv),323            "commands must be nonempty argv arrays")324    return [arg.format_map(substitutions) for arg in argv]325326327def execute(argv, cwd, log):328    with Path(log).open("xb") as output:329        output.write(("+ " + shlex.join(argv) + "\n").encode())330        output.flush()331        with subprocess.Popen(argv, cwd=cwd, stdout=output, stderr=subprocess.STDOUT,332                              start_new_session=True) as child:333            try:334                status = child.wait()335            except BaseException:336                try:337                    os.killpg(child.pid, signal.SIGKILL)338                except ProcessLookupError:339                    pass340                child.wait()341                raise342    require(status == 0, f"gate exited {status}; see {log}")343344345def source_guard(rows):346    return [checked(row) for row in rows]347348349def qualification_inputs(planned, suite, suite_path):350    rows = pinned_inputs(suite.get("inputs"), suite_path.parent)351    rows.append(checked(suite.get("server"), suite_path.parent))352    rows += [record(suite_path), record(Path(__file__)), record(TOOLS / "compatibility.py")]353    rows += source_guard(planned["baseline"]["sources"])354    rows += source_guard(planned["candidate"]["sources"])355    explicit = {row["path"] for row in rows}356    cwd = (suite_path.parent / suite.get("cwd", ".")).resolve(strict=True)357    commands = [suite.get("candidate_build"), *[gate.get("argv") for kind in ("native", "ic")358                                               for gate in suite.get(kind, [])]]359    for argv in commands:360        require(isinstance(argv, list) and argv and isinstance(argv[0], str), "invalid suite command")361        executable = shutil.which(argv[0]) if "/" not in argv[0] else str(cwd / argv[0])362        require(executable is not None, f"suite executable unavailable: {argv[0]}")363        rows.append(record(executable))364        # Script/helper imports remain explicitly declared by the suite author.365        for argument in argv[1:]:366            if "{" not in argument and Path(argument).suffix in (".py", ".sh", ".js", ".mjs"):367                require(str((cwd / argument).resolve(strict=True)) in explicit,368                        f"suite runner must be a pinned input: {argument}")369    return sorted({row["path"]: row for row in rows}.values(), key=lambda row: row["path"])370371372def canonical_builder(argv, inputs):373    require(len(argv) > 1, "candidate build must directly invoke canonical build-app.py")374    # The candidate SDK may be a frozen worktree at a different absolute path.375    path = Path(argv[1]).resolve(strict=True)376    require(path.name == "build-app.py" and sha256_file(path) == sha256_file(TOOLS / path.name),377            "candidate build is not the current canonical builder")378    pinned = {row["path"] for row in inputs}379    require(str(path) in pinned, "candidate builder must be a pinned suite input")380    helper = path.with_name("compatibility.py")381    require(str(helper.resolve()) in pinned and sha256_file(helper) == sha256_file(TOOLS / helper.name),382            "candidate compatibility helper must match the canonical helper and be pinned")383    require("--offline" in argv and "--locked" in argv and "--compatibility-candidate" in argv,384            "candidate build needs --offline --locked --compatibility-candidate")385386387def suite_gates(suite):388    native, ic = suite.get("native"), suite.get("ic")389    require(isinstance(native, list) and native and isinstance(ic, list) and ic,390            "explicit nonempty native and IC gate lists are required")391    require(all(isinstance(gate, dict) and isinstance(gate.get("name"), str) and gate["name"]392                and isinstance(gate.get("contract"), str) and gate["contract"].strip()393                and isinstance(gate.get("argv"), list)394                and all(isinstance(arg, str) and arg for arg in gate["argv"])395                for gate in native + ic), "each gate needs argv, name and reviewed meaning contract")396    require(len({gate["name"] for gate in native + ic}) == len(native + ic), "duplicate gate names")397    coverage = set()398    for gate in native:399        role = gate.get("role")400        require(role in ("baseline", "candidate", "pair"), "native gate needs baseline/candidate/pair role")401        coverage.update(("baseline", "candidate") if role == "pair" else (role,))402        for name in (("baseline", "candidate") if role == "pair" else (role,)):403            require(any("{" + name + "_manifest}" in arg for arg in gate["argv"]),404                    f"native {name} gate must consume its planned manifest")405    require(coverage == {"baseline", "candidate"}, "native gates must cover old and new sources")406    for gate in ic:407        require(all(any("{" + key + "}" in arg for arg in gate["argv"])408                    for key in ("baseline_wasm", "candidate_wasm", "result")),409                "IC gate must consume old/new artifacts and write a fresh result")410    return native, ic411412413def lifecycle(path, baseline, candidate, target, artifacts, server):414    value = document(path, "cdk-rsx-compat-lifecycle-v1")415    require(value.get("target") == target416            and value.get("baseline_sha256") == baseline["sha256"]417            and value.get("candidate_sha256") == candidate["sha256"], "lifecycle artifact/target mismatch")418    require(checked(value.get("server")) == server, "lifecycle server differs from pinned suite")419    checks = value.get("checks", {})420    require(set(checks) == set(CHECKS) and all(checks[key] is True for key in CHECKS),421            "missing, unknown or failed lifecycle checks")422    roles = value.get("artifacts", {})423    require(set(roles) == set(ROLES), "lifecycle needs all exact artifact roles")424    for role in ROLES:425        require(checked(roles[role]) == artifacts[role], f"lifecycle {role} artifact mismatch")426    stages = value.get("stages")427    require(isinstance(stages, list) and stages and all(isinstance(row, dict) for row in stages),428            "lifecycle needs detailed stage evidence")429    sequence = [row.get("stage") for row in stages]430    require(all(name in sequence for name in ("old_state_populated", "forward_keep", "fresh_writes", "reverse_keep"))431            and [sequence.index(name) for name in CHECKS[:4]] == sorted(sequence.index(name) for name in CHECKS[:4]),432            "lifecycle must populate old, KEEP new, write new, then KEEP old")433    for stage, artifact in zip(CHECKS[:4], (baseline, candidate, candidate, baseline)):434        require(stages[sequence.index(stage)].get("sha256") == artifact["sha256"],435                f"lifecycle {stage} used the wrong executable")436    return value437438439def run_qualification(plan_path, suite_path, output_path):440    planned = load_plan(plan_path)441    suite_path = Path(suite_path).resolve(strict=True)442    suite = document(suite_path, "cdk-rsx-compat-suite-v1")443    inputs = qualification_inputs(planned, suite, suite_path)444    server = checked(suite["server"], suite_path.parent)445    native, ic = suite_gates(suite)446    companions = {}447    for role in ROLES[2:]:448        name = suite.get("artifacts", {}).get(role)449        require(isinstance(name, str), f"missing {role} artifact manifest")450        companion = artifact_manifest(Path(suite_path.parent) / name, candidate=True)451        require(companion["configuration"] == planned["baseline"]["configuration"],452                f"{role} fixture changed package/target/features/geometry")453        companions[role] = companion454    output = fresh_output(output_path)455    report = {"format": "cdk-rsx-compat-qualification-v1", "status": "failed", "output": str(output),456              "plan": record(plan_path), "suite": record(suite_path), "aliases": planned["aliases"],457              "changes": planned["changes"], "server": server,458              "inputs": inputs, "gates": [], "companions": companions}459    try:460        substitutions = {"aliases": planned["aliases"]["path"], "output": str(output),461                         "baseline_manifest": planned["baseline"]["manifest"]["path"],462                         "baseline_wasm": planned["baseline"]["wasm"]["path"]}463        build_argv = expand(suite.get("candidate_build"), substitutions)464        canonical_builder(build_argv, inputs)465        alias_index = build_argv.index("--compatibility-candidate")466        require(alias_index + 1 < len(build_argv) and Path(build_argv[alias_index + 1]).resolve()467                == Path(planned["aliases"]["path"]), "candidate builder must use exact plan aliases")468        cwd = (suite_path.parent / suite.get("cwd", ".")).resolve(strict=True)469        log = output / "candidate-build.log"470        execute(build_argv, cwd, log)471        report["build"] = {"argv": build_argv, "log": record(log)}472        candidate_path = suite["candidate_manifest"].format_map(substitutions)473        candidate = artifact_manifest(Path(suite_path.parent) / candidate_path, candidate=True)474        candidate_matches_plan(candidate, planned)475        report["candidate"] = candidate476        for role, companion in companions.items():477            companion_matches(role, companion, candidate, planned)478        artifacts = {"baseline": planned["baseline"]["wasm"], "candidate": candidate["wasm"],479                     **{role: value["wasm"] for role, value in companions.items()}}480        require(len({artifacts[role]["sha256"] for role in ROLES[:5]}) == 5,481                "layout/meaning/unqualified probes must be distinct old/new fixture artifacts")482        report["artifacts"] = artifacts483        substitutions.update(candidate_manifest=candidate["manifest"]["path"], candidate_wasm=candidate["wasm"]["path"])484        for kind, gates in (("native", native), ("ic", ic)):485            for index, gate in enumerate(gates):486                stem = f"{kind}-{index}"487                result = output / f"{stem}.json"488                substitutions["result"] = str(result)489                argv = expand(gate["argv"], substitutions)490                log = output / f"{stem}.log"491                execute(argv, cwd, log)492                evidence = {"kind": kind, "name": gate["name"], "contract": gate["contract"],493                            "role": gate.get("role"), "argv": argv, "log": record(log)}494                if kind == "ic":495                    lifecycle(result, artifacts["baseline"], artifacts["candidate"],496                              candidate["configuration"]["target"], artifacts, server)497                    evidence["result"] = record(result)498                report["gates"].append(evidence)499        source_guard(inputs)500        load_plan(plan_path)501        require(artifact_manifest(candidate["manifest"]["path"], candidate=True) == candidate,502                "candidate artifacts changed during gates")503        for role, companion in companions.items():504            require(artifact_manifest(companion["manifest"]["path"], candidate=True) == companion,505                    f"{role} artifacts changed during gates")506        report["status"] = "passed"507    except BaseException as error:508        report["error"] = str(error)509        write_new(output / "qualification.json", report)510        raise511    return write_new(output / "qualification.json", report)512513514def verify_qualification(path):515    report = document(path, "cdk-rsx-compat-qualification-v1")516    require(report.get("status") == "passed", "qualification did not pass")517    planned = load_plan(checked(report["plan"])["path"])518    suite_path = Path(checked(report["suite"])["path"])519    suite = document(suite_path, "cdk-rsx-compat-suite-v1")520    native, ic = suite_gates(suite)521    checked(report["aliases"])522    require(report["aliases"] == planned["aliases"], "qualification aliases differ from plan")523    require(report["changes"] == planned["changes"], "qualification scope claims differ from plan")524    require(report["inputs"] == qualification_inputs(planned, suite, suite_path),525            "qualification input obligations were changed or dropped")526    require(report["server"] == checked(suite["server"], suite_path.parent), "qualification server changed")527    source_guard(report["inputs"])528    checked(report["build"]["log"])529    candidate = artifact_manifest(report["candidate"]["manifest"]["path"], candidate=True)530    require(candidate == report["candidate"], "tested candidate changed")531    candidate_matches_plan(candidate, planned)532    require(set(report["companions"]) == set(ROLES[2:]), "missing negative fixture manifests")533    for role, companion in report["companions"].items():534        require((suite_path.parent / suite["artifacts"][role]).resolve()535                == Path(companion["manifest"]["path"]), "negative fixture differs from reviewed suite")536        require(artifact_manifest(companion["manifest"]["path"], candidate=True) == companion,537                f"tested {role} fixture changed")538        companion_matches(role, companion, candidate, planned)539        require(report["artifacts"][role] == companion["wasm"], "negative artifact role mismatch")540    require(report["artifacts"]["baseline"] == planned["baseline"]["wasm"]541            and report["artifacts"]["candidate"] == candidate["wasm"], "tested old/new artifacts changed")542    require(set(report["artifacts"]) == set(ROLES)543            and len({report["artifacts"][role]["sha256"] for role in ROLES[:5]}) == 5,544            "qualification roles do not identify distinct fixtures")545    substitutions = {"aliases": planned["aliases"]["path"], "output": report["output"],546                     "baseline_manifest": planned["baseline"]["manifest"]["path"],547                     "baseline_wasm": planned["baseline"]["wasm"]["path"]}548    build_argv = expand(suite["candidate_build"], substitutions)549    canonical_builder(build_argv, report["inputs"])550    require(report["build"]["argv"] == build_argv, "candidate command differs from reviewed suite")551    require((suite_path.parent / suite["candidate_manifest"].format_map(substitutions)).resolve()552            == Path(candidate["manifest"]["path"]), "tested candidate differs from suite output")553    substitutions.update(candidate_manifest=candidate["manifest"]["path"], candidate_wasm=candidate["wasm"]["path"])554    expected = [(kind, index, gate) for kind, gates in (("native", native), ("ic", ic))555                for index, gate in enumerate(gates)]556    require(len(report["gates"]) == len(expected), "suite gates were dropped or added")557    for gate, (kind, index, declared) in zip(report["gates"], expected):558        result_path = Path(report["output"]) / f"{kind}-{index}.json"559        substitutions["result"] = str(result_path)560        require((gate["kind"], gate["name"], gate["contract"], gate.get("role"), gate["argv"])561                == (kind, declared["name"], declared["contract"], declared.get("role"),562                    expand(declared["argv"], substitutions)), "gate differs from reviewed suite")563        checked(gate["log"])564        if kind == "ic":565            require(Path(gate["result"]["path"]) == result_path, "lifecycle result role changed")566            lifecycle(checked(gate["result"])["path"], planned["baseline"]["wasm"], candidate["wasm"],567                      candidate["configuration"]["target"], report["artifacts"], report["server"])568    return report, planned569570571def review_document(path, changes):572    review = document(path, "cdk-rsx-compat-review-v1")573    require(isinstance(review.get("reviewer"), str) and review["reviewer"].strip()574            and review.get("common_class_invariant") is True, "explicit reviewed common-class invariant required")575    rows = review.get("scopes")576    require(isinstance(rows, list) and len(rows) == len(changes), "review must cover every changed scope exactly")577    for row, expected in zip(rows, changes):578        require(all(row.get(key) == value for key, value in expected.items()), "review scope binding changed")579        require(all(isinstance(row.get(key), str) and row[key].strip()580                    for key in ("unchanged_read_interpretation", "unchanged_write_interpretation")),581                "each scope needs unchanged read/write interpretation statements")582    return review583584585@contextmanager586def registry_lock(path):587    spec = importlib.util.spec_from_file_location("canonical_builder", TOOLS / "build-app.py")588    builder = importlib.util.module_from_spec(spec)589    spec.loader.exec_module(builder)590    with builder.locked([path.with_name(path.name + ".lock")]):591        yield592593594def immutable_copy(directory, kind, data):595    digest = hashlib.sha256(data).hexdigest()596    path = directory / f"{digest}.{kind}.json"597    if path.exists():598        require(path.read_bytes() == data, f"conflicting immutable record: {path}")599    else:600        path.parent.mkdir(parents=True, exist_ok=True)601        with path.open("xb") as output:602            output.write(data)603    return path604605606def approve(qualification_path, review_path, registry_path):607    qualification_pin, review_pin = record(qualification_path), record(review_path)608    report, planned = verify_qualification(qualification_path)609    review_document(review_path, planned["changes"])610    registry = Path(registry_path).resolve()611    registry.parent.mkdir(parents=True, exist_ok=True)612    with registry_lock(registry):613        current = document(registry, "cdk-rsx-compat-registry-v1") if registry.exists() else {614            "format": "cdk-rsx-compat-registry-v1", "qualifications": []}615        prior = load_registry(registry)[0] if registry.exists() else EMPTY_ALIASES616        aliases = validate_aliases(load_document(planned["aliases"]["path"]))617        merge_aliases(prior, aliases)  # Conflict check before publishing anything active.618        # Recheck after taking the publication lock, including the review itself.619        verify_qualification(qualification_path)620        review_document(review_path, planned["changes"])621        checked(qualification_pin)622        checked(review_pin)623        directory = registry.parent / "records"624        alias_path = immutable_copy(directory, "aliases", canonical_bytes(aliases))625        report_path = immutable_copy(directory, "qualification", Path(qualification_path).read_bytes())626        review_copy = immutable_copy(directory, "review", Path(review_path).read_bytes())627        approval = {"format": "cdk-rsx-compat-approval-v1", "status": "approved",628                    "aliases_sha256": sha256_file(alias_path),629                    "qualification": dict(record(report_path), path=report_path.name),630                    "review": dict(record(review_copy), path=review_copy.name), "artifacts": {631                        "baseline_sha256": report["artifacts"]["baseline"]["sha256"],632                        "candidate_sha256": report["artifacts"]["candidate"]["sha256"],633                        "target": report["candidate"]["configuration"]["target"]},634                    "evidence": [report["plan"], report["suite"], report["build"]["log"],635                                 *[row[key] for row in report["gates"] for key in ("log", "result") if key in row]]}636        approval_path = immutable_copy(directory, "approval", canonical_bytes(approval))637        row = {"aliases": str(alias_path.relative_to(registry.parent)), "sha256": sha256_file(alias_path),638               "approval": str(approval_path.relative_to(registry.parent)), "approval_sha256": sha256_file(approval_path)}639        if row not in current["qualifications"]:640            current["qualifications"].append(row)641        temporary = registry.with_name(registry.name + f".{os.getpid()}.tmp")642        try:643            with temporary.open("xb") as output:644                output.write(canonical_bytes(current))645                output.flush()646                os.fsync(output.fileno())647            load_registry(temporary)648            temporary.replace(registry)  # The only activation, always last.649        finally:650            temporary.unlink(missing_ok=True)651    return record(registry)652653654def verify_registry(path):655    aliases, _ = load_registry(path)656    registry = document(path, "cdk-rsx-compat-registry-v1")657    for row in registry["qualifications"]:658        approval_path = Path(path).resolve().parent / row["approval"]659        approval = document(approval_path, "cdk-rsx-compat-approval-v1")660        # A portable approval is a reviewed, immutable attestation. Reopening661        # original run artifacts belongs to verify --qualification, not builds.662        report = document(checked(approval["qualification"], approval_path.parent)["path"],663                          "cdk-rsx-compat-qualification-v1")664        review_document(checked(approval["review"], approval_path.parent)["path"], report["changes"])665        require(report["status"] == "passed" and report["aliases"]["sha256"] == row["sha256"],666                "approval does not bind the tested alias payload")667        require(approval["artifacts"]["baseline_sha256"] == report["artifacts"]["baseline"]["sha256"]668                and approval["artifacts"]["candidate_sha256"] == report["artifacts"]["candidate"]["sha256"],669                "approval artifact binding changed")670    return aliases671672673def main(argv=None):674    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)675    commands = parser.add_subparsers(dest="command", required=True)676    item = commands.add_parser("preflight", help="compare compiler policies in two completed build receipts")677    item.add_argument("--baseline", required=True)678    item.add_argument("--candidate", required=True)679    item = commands.add_parser("plan")680    item.add_argument("--baseline", required=True)681    item.add_argument("--candidate", required=True)682    item.add_argument("--output", required=True)683    item = commands.add_parser("run")684    item.add_argument("--plan", required=True)685    item.add_argument("--suite", required=True)686    item.add_argument("--output", required=True)687    item = commands.add_parser("approve")688    item.add_argument("--qualification", required=True)689    item.add_argument("--review", required=True)690    item.add_argument("--registry", required=True)691    item = commands.add_parser("verify")692    choice = item.add_mutually_exclusive_group(required=True)693    choice.add_argument("--qualification")694    choice.add_argument("--registry")695    choice.add_argument("--plan")696    args = parser.parse_args(argv)697    try:698        if args.command == "preflight":699            result = preflight(args.baseline, args.candidate)700            print(json.dumps(result, indent=2))701            return 0 if result["status"] == "compiler-policy-match" else 1702        if args.command == "plan":703            result = plan(args.baseline, args.candidate, args.output)704        elif args.command == "run":705            result = run_qualification(args.plan, args.suite, args.output)706        elif args.command == "approve":707            result = approve(args.qualification, args.review, args.registry)708        elif args.registry:709            result = {"verified": str(Path(args.registry).resolve()),710                      "entries": len(verify_registry(args.registry)["entries"])}711        elif args.plan:712            result = {"verified": str(Path(args.plan).resolve()),713                      "changed_scopes": len(load_plan(args.plan)["changes"])}714        else:715            result = {"verified": str(Path(args.qualification).resolve()),716                      "gates": len(verify_qualification(args.qualification)[0]["gates"])}717        print(json.dumps(result, sort_keys=True))718        return 0719    except (ValueError, OSError, KeyError, TypeError) as error:720        if args.command == "preflight":721            print(f"KEEP preflight rejected: {error}", file=sys.stderr)722            return 2723        print(f"compatibility qualification rejected: {error}", file=sys.stderr)724        return 1725726727if __name__ == "__main__":728    sys.exit(main())