hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
"""Offline authentication of finite claims and actual direct Native9 launch/proof envelopes."""

from pathlib import Path
from c2_matrix_io import digest, integer, payload, require, resolve
from c2_controller_state_authority import PREFIX, closed, authority, file_bytes, check_sources
from c2_controller_state_runtime import (native_cleanup)


def spend_claims_checked(context, packet, decision, plan, prepared_pairs):
    """Join the exact two immutable reservations to both actual stopped roles.

    Exclusive creation/outer argv custody must additionally be authenticated by
    the source-reviewed Native9 launcher envelope, never by these JSON values.
    """
    from datetime import datetime, timezone
    require(type(prepared_pairs) in (tuple, list) and len(prepared_pairs) == 2,
            "both actual stopped Native9 roles required")
    spend = authority(context["spend_index"])
    closed(spend, "schema plan owner_decision claims model_start_attempts complete", "actual one-case spend index")
    require(spend["schema"] == PREFIX + "spend-index.v1" and spend["plan"] == decision["prospective_plan"]
            and spend["owner_decision"] == packet["owner_decision"] and spend["complete"] is True
            and type(spend["claims"]) is list and len(spend["claims"]) == 2,
            "whole immutable two-role spend custody absent")
    integer(spend["model_start_attempts"], "actual model-start attempts", 2, 2)
    nonces, claims = set(), []
    for ordinal, (binding, role, pair) in enumerate(zip(spend["claims"], plan["roles"], prepared_pairs)):
        prepared_binding, prepared, receipt_binding, receipt = pair
        require(binding["path"] == role["claim_path"], "actual start claim not at original immutable reservation")
        claim = authority(binding)
        closed(claim, "schema plan owner_decision role ordinal id output prepared native_driver argv claimed_utc nonce", "actual immutable model-start claim")
        require(claim["schema"] == PREFIX + "start-claim.v1" and claim["plan"] == decision["prospective_plan"]
                and claim["owner_decision"] == packet["owner_decision"] and claim["ordinal"] == ordinal,
                "actual start claim belongs to another current plan/owner/ordinal")
        integer(claim["ordinal"], "actual claimed start ordinal", 0, 1)
        for key in ("role", "id", "output", "native_driver"):
            require(claim[key] == role[key], "actual start claim changed reserved " + key)
        require(claim["prepared"] == prepared_binding and prepared_binding["path"] == role["prepared_path"]
                and prepared["output"] == role["output"] and receipt["mode"] == role["role"],
                "actual Native9 role/prepared/output differs from original immutable reservation")
        require(prepared["file_sha256"].get(role["native_driver"]["path"]) == role["native_driver"]["sha256"],
                "actual Native9 runtime omitted its reviewed launcher source")
        require(Path(receipt_binding["path"]) == Path(role["output"]) / "receipt.json", "actual Native9 role receipt namespace differs")
        require(type(claim["argv"]) is list and claim["argv"]
                and all(type(arg) is str and arg for arg in claim["argv"])
                and role["claim_controller"]["path"] in claim["argv"],
                "actual launcher argv absent/wrong source")
        require(type(claim["claimed_utc"]) is str and claim["claimed_utc"], "actual UTC claim timestamp absent")
        at = datetime.fromisoformat(claim["claimed_utc"].replace("Z", "+00:00"))
        require(at.tzinfo is not None and at.utcoffset() == timezone.utc.utcoffset(at), "claim time is not actual timezone-aware UTC")
        nonce = digest(claim["nonce"])
        require(nonce not in nonces, "model-start claim nonce reused")
        nonces.add(nonce)
        claims.append((binding, claim))
    return spend, claims


def native_outer_checked(manifest_ref, receipt_ref, expected_argv, native_outer_ref, context):
    """Authenticate the DIRECT Native9 unit, not the old strict-child suffix."""
    manifest, receipt = authority(manifest_ref), authority(receipt_ref)
    require(manifest["schema"] == "hf2q.private.native-owned-outer-manifest.v4"
            and set(manifest["units"]) == {"outer"}
            and receipt["schema"] == "hf2q.private.bounded-native-outer-proof.v4"
            and receipt["unit"] == "outer"
            and receipt["manifest_sha256"] == manifest_ref["sha256"]
            and receipt["source"] == manifest["source"]
            and receipt["argv"] == manifest["units"]["outer"]["argv"] == expected_argv,
            "actual direct Native9 outer source/unit/whole invocation differs")
    expected_root = Path(manifest_ref["path"]).parent / "runs" / "outer"
    require(Path(receipt_ref["path"]) == expected_root / "receipt.json",
            "actual direct Native9 receipt not in original fixed-unit output namespace")
    require(receipt["passed"] is True and receipt["cleanup_proven"] is True
            and receipt["exit_code"] == 0 and receipt["stop"] is None
            and receipt["model_or_performance_gate"] is False,
            "actual independently owned Native9 outer did not settle successfully")
    native_cleanup(receipt)
    check_sources(manifest["file_sha256"])
    check_sources(receipt["ownership_source_sha256"])
    require(receipt["ownership_source_sha256"].items() <= manifest["file_sha256"].items()
            and manifest["runner_sha256"] == native_outer_ref["sha256"]
            and manifest["file_sha256"].get(native_outer_ref["path"]) == native_outer_ref["sha256"]
            and context["native9_source_bindings"].get(native_outer_ref["path"]) == native_outer_ref["sha256"],
            "actual outer is not the exact independently proven Native9 source")
    owner_sources = {path: sha for path, sha in context["native9_source_bindings"].items()
                     if Path(path).name == "native_owned.py"}
    require(len(owner_sources) == 1 and owner_sources.items() <= receipt["ownership_source_sha256"].items(),
            "actual native owner source/proof closure differs")
    known = receipt["known_owned_lifetimes"]
    require(type(known) is list and known
            and len({(row["pid"], row["lifetime_id"]) for row in known}) == len(known)
            and any(row["pid"] == row["pgid"] == receipt["pid"] for row in known)
            and all(type(row["pid"]) is int and row["pid"] > 1 and type(row["pgid"]) is int and row["pgid"] > 1
                    and type(row["lifetime_id"]) is str and row["lifetime_id"].startswith("darwin-unique:")
                    and type(row["pid_version"]) is int and row["pid_version"] >= 0 for row in known)
            and receipt["cleanup"]["pgids"] == sorted({row["pgid"] for row in known}),
            "actual Native9 kernel-root lifetime/exec cohort absent")
    for name in ("stdout", "stderr"):
        path = expected_root / (name + ".log")
        payload(path, receipt[name + "_sha256"], path.stat().st_size)
    return manifest, receipt, expected_root


def reviewed_launcher_sources_checked(review, prepared_pairs):
    """Keep compiled CORE sources distinct from the complete prepared runtime."""
    sources = authority(review["source_manifest"])
    controller, outer = review["claim_controller"], review["native_outer"]
    require(sources["file_sha256"].get(controller["path"]) == controller["sha256"],
            "reviewed claim controller absent from compiled source closure")
    for _, prepared, _, _ in prepared_pairs:
        require(prepared["file_sha256"].get(outer["path"]) == outer["sha256"],
                "reviewed external Native9 outer absent from complete prepared runtime closure")
    return sources


def launch_envelopes_checked(context, packet, decision, plan, claims, prepared_pairs):
    review = authority(context["launch_source_review"])
    closed(review, "schema source_manifest claim_controller native_outer reviewer properties verdict proof", "actual launch source review")
    roles = plan["roles"]
    require(review["schema"] == PREFIX + "launch-source-review.v1" and review["verdict"] == "Accepted"
            and review["source_manifest"] == context["source_manifest"]
            and review["claim_controller"] == roles[0]["claim_controller"]
            and review["native_outer"] == roles[0]["native_outer"]
            and type(review["reviewer"]) is str and review["reviewer"].strip()
            and all(review["reviewer"] != pair[1]["config"]["root_identity"] for pair in prepared_pairs),
            "actual independently reviewed current claim/native launcher source absent")
    properties = closed(review["properties"],
        "exclusive_create_fsync_before_preflight fixed_two_roles_no_retry native_outer_actual_argv_join no_namespace_reset",
        "actual launch source review properties")
    require(all(value is True for value in properties.values()), "independent launch source review incomplete")
    sources = reviewed_launcher_sources_checked(review, prepared_pairs)
    proof = authority(review["proof"])
    closed(proof, "schema source_manifest claim_controller native_outer native9_transition_proof cpu_proof_source cpu_outer_manifest cpu_outer_receipt cpu_invocation cases model_starts", "actual model-free launch proof")
    require(proof["schema"] == PREFIX + "launch-proof.v1"
            and proof["source_manifest"] == review["source_manifest"]
            and proof["claim_controller"] == review["claim_controller"]
            and proof["native_outer"] == review["native_outer"]
            and proof["native9_transition_proof"] == context["native9_proof"]
            and proof["cases"] == ["duplicate_claim_refused_before_exec", "preflight_refusal_spends_claim",
                                  "exec_matches_outer_argv", "cleanup_and_no_namespace_reset"],
            "actual independently reviewed control-process regression proof differs")
    integer(proof["model_starts"], "actual control proof model starts", 0, 0)
    cpu_source = proof["cpu_proof_source"]
    cpu_path = resolve(Path("/"), cpu_source, absolute=True)
    payload(cpu_path, cpu_source["sha256"], cpu_path.stat().st_size)
    require(sources["file_sha256"].get(cpu_source["path"]) == cpu_source["sha256"],
            "actual executed CPU assertions source not in reviewed source closure")
    invocation = closed(proof["cpu_invocation"], "argv cwd exit_code stdout stderr", "actual independent CPU invocation")
    require(type(invocation["argv"]) is list and cpu_source["path"] in invocation["argv"],
            "actual CPU proof did not invoke its bound assertions program")
    cpu_manifest, cpu_receipt, cpu_root = native_outer_checked(
        proof["cpu_outer_manifest"], proof["cpu_outer_receipt"], invocation["argv"], review["native_outer"], context)
    require(invocation["cwd"] == cpu_manifest["cwd"] and Path(invocation["cwd"]).is_absolute()
            and invocation["exit_code"] == cpu_receipt["exit_code"] == 0
            and cpu_manifest["file_sha256"].get(cpu_source["path"]) == cpu_source["sha256"],
            "actual model-free regression invocation/source/exit differs")
    for name in ("stdout", "stderr"):
        require(invocation[name] == {"path": str(cpu_root / (name + ".log")), "sha256": cpu_receipt[name + "_sha256"]},
                "actual CPU proof raw stdio binding differs")
        file_bytes(invocation[name])
    index = authority(context["launch_envelopes"])
    closed(index, "schema plan owner_decision roles", "actual two-role launch index")
    require(index["schema"] == PREFIX + "launch-index.v1" and index["plan"] == decision["prospective_plan"]
            and index["owner_decision"] == packet["owner_decision"]
            and type(index["roles"]) is list and len(index["roles"]) == 2,
            "whole actual two-role launch envelope inventory absent")
    for ordinal, (value, role, claimed, pair) in enumerate(zip(index["roles"], roles, claims, prepared_pairs)):
        closed(value, "ordinal role claim outer_manifest outer_receipt", "actual launch role")
        claim_ref, claim = claimed
        prepared_ref, prepared, diagnostic_ref, diagnostic = pair
        integer(value["ordinal"], "actual launch role ordinal", 0, 1)
        require(value["ordinal"] == ordinal and value["role"] == role["role"] and value["claim"] == claim_ref
                and value["outer_manifest"]["path"] == role["outer_manifest_path"]
                and value["outer_receipt"]["path"] == role["outer_receipt_path"],
                "actual launch/claim/role/output reservation changed")
        manifest, outer, _ = native_outer_checked(
            value["outer_manifest"], value["outer_receipt"], claim["argv"], role["native_outer"], context)
        for binding in (claim["prepared"], claim["plan"], claim["owner_decision"],
                        role["claim_controller"], role["native_driver"]):
            require(manifest["file_sha256"].get(binding["path"]) == binding["sha256"],
                    "actual Native9 invocation omitted immutable authority/prepared/launcher binding")
        # Same Darwin lifetime, not PID alone and not scheduler/native counters.
        outer_lifetimes = {(row["pid"], row["lifetime_id"]) for row in outer["known_owned_lifetimes"]}
        model_lifetimes = {(row["pid"], row["lifetime_id"]) for row in diagnostic["known_owned_lifetimes"]
                           if row["pid"] == diagnostic["pid"]}
        require(model_lifetimes and model_lifetimes <= outer_lifetimes,
                "diagnostic model child is not in the independently observed Native9 outer root")
    return context["launch_envelopes"], context["launch_source_review"]