#!/usr/bin/env python3
"""Fail-closed exact-candidate privacy-portability execution.

The public launcher has no caller-selectable implementation, oracle, isolation
provider, toolchain, or signing authority.  Those trust decisions live in one
digest-pinned package policy.  The current policy is deliberately disabled, so
the live package cannot produce positive execution evidence.

The isolation primitive and independent oracle are separately testable in a
temporary fixture.  Candidate output is only opaque response bytes: candidates
cannot declare predicates, relationships, digests, or pass/fail outcomes.
"""
from __future__ import annotations

import argparse
import base64
import binascii
import datetime as dt
import fcntl
import hashlib
import json
import math
import os
import re
import secrets
import stat
import subprocess
import tempfile
import time
from pathlib import Path, PurePosixPath

SHA256 = re.compile(r"^[0-9a-f]{64}$")
COMMIT = re.compile(r"^[0-9a-f]{40}$")
TESTS = {
    "privacy.commitment-reuse",
    "privacy.cross-partner-collusion",
    "privacy.metadata-timing-correlation",
}
SAMPLES_PER_TEST = 400
DOMAIN_CONTENT = b"vaultfire-unlinkability-content-v3\0"
DOMAIN_PAIR = b"vaultfire-unlinkability-pair-v3\0"
DOMAIN_SELECTION = b"vaultfire-unlinkability-selection-v1\0"
DOMAIN_OUTPUT = b"vaultfire-unlinkability-output-v4\0"
DOMAIN_RECEIPT = b"vaultfire-unlinkability-execution-receipt-v1\0"
DOMAIN_GENERATION = b"vaultfire-unlinkability-generation-v1\0"
RELATIONSHIP_SAMPLES_PER_CLASS = SAMPLES_PER_TEST // 2
CONFIDENCE_NUMERATOR = 95
CONFIDENCE_DENOMINATOR = 100
MAX_RELATIONSHIP_ERROR_UPPER_BPS = 1000

PACKAGE_REL = PurePosixPath("pr10/partner-package")
RUNNER_REL = "pr10/partner-package/scripts/run_unlinkability_protocol.py"
POLICY_REL = "pr10/partner-package/config/privacy-execution-trust-policy.json"
PINNED_POLICY_SHA256 = (
    "b3a4b647a8b2e0259373b4d59b4eb69f3e5ad6e8176efc52e401dcf00c40a348"
)
CANONICAL_IMPLEMENTATION_PATH = "v3-src/privacy-portability/canonical_api.py"
CANONICAL_INTERFACE_ID = "vaultfire.privacy-portability.cli-v1"
INDEPENDENT_ORACLE_ID = "vaultfire.privacy-portability.oracle-v1"
EMPTY_SHA256 = hashlib.sha256(b"").hexdigest()


def canonical(value: object) -> bytes:
    return json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    ).encode()


def sha(domain: bytes, value: object) -> str:
    return hashlib.sha256(domain + canonical(value)).hexdigest()


def strict_object(text: str) -> dict:
    def pairs(items: list[tuple[str, object]]) -> dict:
        out: dict = {}
        for key, value in items:
            if key in out:
                raise ValueError(f"duplicate JSON key: {key}")
            out[key] = value
        return out

    value = json.loads(
        text,
        object_pairs_hook=pairs,
        parse_constant=lambda token: (_ for _ in ()).throw(
            ValueError(f"non-finite JSON value: {token}")
        ),
    )
    if type(value) is not dict:
        raise ValueError("JSON value must be an object")
    return value


def valid_digest(value: object) -> bool:
    return type(value) is str and SHA256.fullmatch(value) is not None


def _open_absolute_nofollow(path: Path, *, directory: bool, label: str) -> int:
    """Open an absolute path from the trusted filesystem root without aliases.

    Every component is lstat'ed, opened with O_NOFOLLOW, and compared by
    device/inode before and after open.  The returned descriptor pins the
    object even if a concurrent rename occurs.
    """
    if not path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts[1:]):
        raise ValueError(f"{label} path must be canonical and absolute")
    cursor_fd = os.open("/", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    try:
        for index, part in enumerate(path.parts[1:]):
            final = index == len(path.parts[1:]) - 1
            before = os.stat(part, dir_fd=cursor_fd, follow_symlinks=False)
            wanted_directory = not final or directory
            if wanted_directory and not stat.S_ISDIR(before.st_mode):
                raise ValueError(f"{label} path contains a non-directory component")
            if final and not directory and (
                not stat.S_ISREG(before.st_mode) or before.st_nlink != 1
            ):
                raise ValueError(f"{label} must be one unique regular file")
            flags = os.O_RDONLY | os.O_NOFOLLOW
            if wanted_directory:
                flags |= os.O_DIRECTORY
            next_fd = os.open(part, flags, dir_fd=cursor_fd)
            opened = os.fstat(next_fd)
            after = os.stat(part, dir_fd=cursor_fd, follow_symlinks=False)
            identity = (opened.st_dev, opened.st_ino)
            if identity != (before.st_dev, before.st_ino) or identity != (
                after.st_dev,
                after.st_ino,
            ):
                os.close(next_fd)
                raise ValueError(f"{label} path changed during no-follow traversal")
            os.close(cursor_fd)
            cursor_fd = next_fd
        return cursor_fd
    except Exception:
        os.close(cursor_fd)
        raise


def _fd_digest(fd: int) -> str:
    state = hashlib.sha256()
    os.lseek(fd, 0, os.SEEK_SET)
    while True:
        chunk = os.read(fd, 1024 * 1024)
        if not chunk:
            break
        state.update(chunk)
    return state.hexdigest()


def _digest(path: Path) -> str:
    fd = _open_absolute_nofollow(path.absolute(), directory=False, label="digest input")
    try:
        return _fd_digest(fd)
    finally:
        os.close(fd)


def _tree_digest(root: Path) -> str:
    state = hashlib.sha256()
    count = 0
    root_fd = _open_absolute_nofollow(
        root.absolute(), directory=True, label="toolchain tree"
    )

    def visit(directory_fd: int, prefix: tuple[str, ...]) -> None:
        nonlocal count
        for name in sorted(os.listdir(directory_fd)):
            parts = prefix + (name,)
            if "__pycache__" in parts or name.endswith((".pyc", ".pyo")):
                raise ValueError("toolchain tree contains prohibited bytecode")
            before = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
            if stat.S_ISLNK(before.st_mode):
                raise ValueError("toolchain tree contains a symlink")
            if stat.S_ISDIR(before.st_mode):
                child_fd = os.open(
                    name,
                    os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
                    dir_fd=directory_fd,
                )
                try:
                    opened = os.fstat(child_fd)
                    after = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
                    if (opened.st_dev, opened.st_ino) != (
                        before.st_dev,
                        before.st_ino,
                    ) or (opened.st_dev, opened.st_ino) != (
                        after.st_dev,
                        after.st_ino,
                    ):
                        raise ValueError("toolchain tree changed during traversal")
                    visit(child_fd, parts)
                finally:
                    os.close(child_fd)
                continue
            if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1:
                raise ValueError("toolchain tree contains a non-unique regular file")
            file_fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory_fd)
            try:
                opened = os.fstat(file_fd)
                after = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
                if (opened.st_dev, opened.st_ino) != (
                    before.st_dev,
                    before.st_ino,
                ) or (opened.st_dev, opened.st_ino) != (
                    after.st_dev,
                    after.st_ino,
                ):
                    raise ValueError("toolchain tree changed during traversal")
                rel = "/".join(parts).encode()
                state.update(len(rel).to_bytes(4, "big"))
                state.update(rel)
                state.update(bytes.fromhex(_fd_digest(file_fd)))
                count += 1
            finally:
                os.close(file_fd)

    try:
        visit(root_fd, ())
    finally:
        os.close(root_fd)
    if count == 0:
        raise ValueError("toolchain tree is empty")
    return state.hexdigest()


def _canonical_regular_file(root: Path, rel_text: str, label: str) -> Path:
    pure = PurePosixPath(rel_text)
    if (
        pure.is_absolute()
        or pure.as_posix() != rel_text
        or "\\" in rel_text
        or any(part in {"", ".", ".."} for part in pure.parts)
    ):
        raise ValueError(f"{label} path is noncanonical")
    root_fd = _open_absolute_nofollow(
        root.absolute(), directory=True, label=f"{label} trusted root"
    )
    cursor_fd = root_fd
    try:
        for index, part in enumerate(pure.parts):
            final = index == len(pure.parts) - 1
            before = os.stat(part, dir_fd=cursor_fd, follow_symlinks=False)
            if final:
                if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1:
                    raise ValueError(
                        f"{label} must be one unique regular file, not an alias"
                    )
                flags = os.O_RDONLY | os.O_NOFOLLOW
            else:
                if not stat.S_ISDIR(before.st_mode):
                    raise ValueError(f"{label} path contains a non-directory")
                flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
            next_fd = os.open(part, flags, dir_fd=cursor_fd)
            opened = os.fstat(next_fd)
            after = os.stat(part, dir_fd=cursor_fd, follow_symlinks=False)
            if (opened.st_dev, opened.st_ino) != (
                before.st_dev,
                before.st_ino,
            ) or (opened.st_dev, opened.st_ino) != (after.st_dev, after.st_ino):
                os.close(next_fd)
                raise ValueError(f"{label} path changed during traversal")
            if cursor_fd != root_fd:
                os.close(cursor_fd)
            cursor_fd = next_fd
        return root.joinpath(*pure.parts)
    finally:
        if cursor_fd != root_fd:
            os.close(cursor_fd)
        os.close(root_fd)


def wrapped_content(path: str | Path, expected_type: str) -> bytes:
    wrapper = strict_object(Path(path).read_text())
    if (
        set(wrapper)
        not in (
            {
                "recordType",
                "inputType",
                "inputContentBase64",
                "inputContentSha256",
            },
            {
                "schemaVersion",
                "recordType",
                "candidateId",
                "sourceCommit",
                "gitTree",
                "scopeSha256",
                "chain",
                "inputType",
                "methodologyId",
                "createdAtUtc",
                "inputContentBase64",
                "inputContentSha256",
                "itemCount",
                "containsRawPersonalData",
                "containsSurveillanceInputs",
            },
        )
        or wrapper.get("recordType") != "privacy-unlinkability-methodology-input"
        or wrapper.get("inputType") != expected_type
        or type(wrapper.get("inputContentBase64")) is not str
        or not valid_digest(wrapper.get("inputContentSha256"))
    ):
        raise ValueError(f"{expected_type} wrapper invalid")
    try:
        content = base64.b64decode(wrapper["inputContentBase64"], validate=True)
    except (ValueError, binascii.Error) as exc:
        raise ValueError(f"{expected_type} wrapper encoding invalid") from exc
    if (
        not content
        or hashlib.sha256(content).hexdigest()
        != wrapper["inputContentSha256"]
    ):
        raise ValueError(f"{expected_type} wrapper digest mismatch")
    return content


def validate_context(context: dict) -> None:
    exact = {
        "protocolId",
        "candidateId",
        "sourceCommit",
        "gitTree",
        "scopeSha256",
        "seedOpeningSha256",
        "seedCommitmentSha256",
        "corpusUniverseSha256",
        "selectionManifestSha256",
        "evaluationContextSha256",
        "runnerSha256",
        "executablePath",
        "executableSha256",
        "executionPolicySha256",
        "candidateImplementationPath",
        "candidateImplementationSha256",
        "candidateImplementationGitBlob",
        "candidateInterfaceId",
        "candidateModuleId",
        "candidateRouteId",
        "independentOracleId",
        "argvTemplate",
    }
    if set(context) != exact:
        raise ValueError("execution context fields are not exact")
    if context["protocolId"] != "vaultfire-unlinkability-execution-v4":
        raise ValueError("protocol is not canonical v4")
    if not re.fullmatch(r"sha256:[0-9a-f]{64}", context["candidateId"] or ""):
        raise ValueError("candidateId malformed")
    for key in ("sourceCommit", "gitTree", "candidateImplementationGitBlob"):
        if type(context[key]) is not str or COMMIT.fullmatch(context[key]) is None:
            raise ValueError(f"{key} malformed")
    for key in (
        "scopeSha256",
        "seedOpeningSha256",
        "seedCommitmentSha256",
        "corpusUniverseSha256",
        "selectionManifestSha256",
        "evaluationContextSha256",
        "runnerSha256",
        "executableSha256",
        "executionPolicySha256",
        "candidateImplementationSha256",
    ):
        if not valid_digest(context[key]):
            raise ValueError(f"{key} malformed")
    if (
        context["executablePath"] != RUNNER_REL
        or context["runnerSha256"] != context["executableSha256"]
        or context["executionPolicySha256"] != PINNED_POLICY_SHA256
        or context["candidateImplementationPath"]
        != CANONICAL_IMPLEMENTATION_PATH
        or context["candidateInterfaceId"] != CANONICAL_INTERFACE_ID
        or context["independentOracleId"] != INDEPENDENT_ORACLE_ID
    ):
        raise ValueError("canonical runner/implementation/oracle identity mismatch")
    if _digest(Path(__file__)) != context["runnerSha256"]:
        raise ValueError("runner digest does not match executing bytes")
    expected_argv = [
        "--execute-candidate-protocol",
        "--context",
        "{contextPath}",
        "--corpus-universe",
        "{corpusUniversePath}",
        "--selection",
        "{selectionPath}",
        "--selection-commit",
        "{selectionCommit}",
        "--selection-tree",
        "{selectionTree}",
        "--raw-events",
        "{rawEventsPath}",
        "--execution-record",
        "{executionRecordPath}",
        "--test-id",
        "{testId}",
    ]
    if context["argvTemplate"] != expected_argv:
        raise ValueError("argvTemplate is not the complete canonical invocation")
    for key in ("candidateModuleId", "candidateRouteId"):
        if type(context[key]) is not str or not context[key]:
            raise ValueError(f"{key} malformed")


def side_content(side: dict) -> dict:
    exact = {
        "contentId",
        "subjectCommitmentSha256",
        "partnerContextSha256",
        "chainId",
        "nonceSha256",
        "caseInputBase64",
        "caseInputSha256",
    }
    if (
        set(side) != exact
        or type(side["chainId"]) is not str
        or side["chainId"] not in {"base", "ethereum", "solana"}
    ):
        raise ValueError("challenge side fields are not exact")
    for key in (
        "subjectCommitmentSha256",
        "partnerContextSha256",
        "nonceSha256",
        "caseInputSha256",
    ):
        if not valid_digest(side[key]):
            raise ValueError(f"challenge {key} malformed")
    try:
        raw = base64.b64decode(side["caseInputBase64"], validate=True)
    except (ValueError, binascii.Error) as exc:
        raise ValueError("case input encoding invalid") from exc
    if not raw or hashlib.sha256(raw).hexdigest() != side["caseInputSha256"]:
        raise ValueError("case input digest mismatch")
    body = {key: side[key] for key in sorted(exact - {"contentId"})}
    if side["contentId"] != "content:" + sha(DOMAIN_CONTENT, body):
        raise ValueError("contentId is not derived from challenge content")
    return body


def validate_pair(row: dict) -> tuple[dict, dict]:
    if set(row) != {"pairId", "testId", "left", "right"} or row["testId"] not in TESTS:
        raise ValueError("corpus row fields are not exact")
    left, right = side_content(row["left"]), side_content(row["right"])
    if row["left"]["contentId"] == row["right"]["contentId"]:
        raise ValueError("degenerate corpus pair")
    body = {
        "testId": row["testId"],
        "contentIds": sorted(
            [row["left"]["contentId"], row["right"]["contentId"]]
        ),
    }
    if row["pairId"] != "pair:" + sha(DOMAIN_PAIR, body):
        raise ValueError("pairId is not content-derived")
    return left, right


def derive_selection(rows: list[dict], seed: bytes) -> list[str]:
    if type(seed) is not bytes or len(seed) != 32:
        raise ValueError("seed opening must be exactly 32 bytes")
    seen_pairs: set[str] = set()
    seen_unordered: set[frozenset[str]] = set()
    groups: dict[str, dict[str, list[tuple[str, str]]]] = {
        test: {"linked": [], "unlinked": []} for test in TESTS
    }
    for row in rows:
        validate_pair(row)
        unordered = frozenset(
            (row["left"]["contentId"], row["right"]["contentId"])
        )
        if row["pairId"] in seen_pairs or unordered in seen_unordered:
            raise ValueError("duplicate or reversed corpus pair")
        seen_pairs.add(row["pairId"])
        seen_unordered.add(unordered)
        rank = hashlib.sha256(
            DOMAIN_SELECTION + seed + row["pairId"].encode()
        ).hexdigest()
        relationship = _expected_relationship(row)
        groups[row["testId"]][relationship].append((rank, row["pairId"]))
    selected: list[str] = []
    for test in sorted(TESTS):
        for relationship in ("linked", "unlinked"):
            if len(groups[test][relationship]) < RELATIONSHIP_SAMPLES_PER_CLASS:
                raise ValueError(
                    "corpus universe lacks mandatory per-test relationship coverage"
                )
            selected.extend(
                pair
                for _, pair in sorted(groups[test][relationship])[
                    :RELATIONSHIP_SAMPLES_PER_CLASS
                ]
            )
    return sorted(
        selected,
        key=lambda pair: hashlib.sha256(
            DOMAIN_SELECTION + seed + pair.encode()
        ).hexdigest(),
    )


def _expected_relationship(row: dict) -> str:
    return (
        "linked"
        if (
            row["left"]["subjectCommitmentSha256"],
            row["left"]["partnerContextSha256"],
            row["left"]["chainId"],
        )
        == (
            row["right"]["subjectCommitmentSha256"],
            row["right"]["partnerContextSha256"],
            row["right"]["chainId"],
        )
        else "unlinked"
    )


def _conservative_upper_bps(errors: int, samples: int) -> int:
    if (
        type(errors) is not int
        or type(samples) is not int
        or errors < 0
        or samples <= 0
        or errors > samples
    ):
        raise ValueError("relationship confidence inputs are invalid")
    # One-sided Hoeffding at 95%, computed upward so integer conversion can
    # never understate the conservative bound.
    epsilon = math.sqrt(
        math.log(CONFIDENCE_DENOMINATOR / (CONFIDENCE_DENOMINATOR - CONFIDENCE_NUMERATOR))
        / (2 * samples)
    )
    return min(10000, math.ceil((errors / samples + epsilon) * 10000))


def _relationship_verdict(events: list[dict]) -> dict:
    linked = [event for event in events if event["expectedRelationship"] == "linked"]
    unlinked = [event for event in events if event["expectedRelationship"] == "unlinked"]
    if not linked or not unlinked:
        raise ValueError("unlinkability verdict requires both relationship classes")
    false_negatives = sum(
        event["observedRelationship"] != "linked" for event in linked
    )
    false_positives = sum(
        event["observedRelationship"] != "unlinked" for event in unlinked
    )
    total = len(events)
    combined_errors = false_negatives + false_positives
    verdict = {
        "confidenceNumerator": CONFIDENCE_NUMERATOR,
        "confidenceDenominator": CONFIDENCE_DENOMINATOR,
        "linkedSamples": len(linked),
        "truePositives": len(linked) - false_negatives,
        "falseNegatives": false_negatives,
        "falseNegativeUpperBoundBps": _conservative_upper_bps(
            false_negatives, len(linked)
        ),
        "unlinkedSamples": len(unlinked),
        "trueNegatives": len(unlinked) - false_positives,
        "falsePositives": false_positives,
        "falsePositiveUpperBoundBps": _conservative_upper_bps(
            false_positives, len(unlinked)
        ),
        "combinedSamples": total,
        "combinedErrors": combined_errors,
        "combinedErrorUpperBoundBps": _conservative_upper_bps(
            combined_errors, total
        ),
    }
    verdict["passed"] = (
        verdict["falseNegativeUpperBoundBps"] <= MAX_RELATIONSHIP_ERROR_UPPER_BPS
        and verdict["falsePositiveUpperBoundBps"]
        <= MAX_RELATIONSHIP_ERROR_UPPER_BPS
        and verdict["combinedErrorUpperBoundBps"]
        <= MAX_RELATIONSHIP_ERROR_UPPER_BPS
    )
    if not verdict["passed"]:
        raise ValueError("unlinkability relationship verdict failed closed")
    return verdict


def _policy(repo: Path) -> dict:
    path = _canonical_regular_file(repo, POLICY_REL, "execution trust policy")
    if _digest(path) != PINNED_POLICY_SHA256:
        raise ValueError("execution trust policy differs from the pinned digest")
    policy = strict_object(path.read_text())
    if (
        policy.get("status") != "reviewed-candidate-bound"
        or policy.get("positiveReadinessAllowed") is not True
    ):
        raise ValueError(
            "privacy execution is structurally disabled: no genuine pinned authority"
        )
    return policy


def _validate_exact_host_toolchain(policy: dict) -> None:
    isolation, toolchain = policy["isolation"], policy["toolchain"]
    for key, label in (
        ("binaryPath", "isolation binary"),
        ("pythonPath", "python binary"),
    ):
        value = isolation[key] if key == "binaryPath" else toolchain[key]
        if type(value) is not str or not Path(value).is_absolute():
            raise ValueError(f"{label} path is not pinned")
        descriptor = _open_absolute_nofollow(
            Path(value), directory=False, label=label
        )
        os.close(descriptor)
    if _digest(Path(isolation["binaryPath"])) != isolation["binarySha256"]:
        raise ValueError("isolation binary digest mismatch")
    version = subprocess.run(
        [isolation["binaryPath"], "--version"],
        capture_output=True,
        text=True,
        timeout=5,
        check=False,
        env={"PATH": ""},
    )
    if version.returncode != 0 or version.stdout.strip() != isolation["binaryVersion"]:
        raise ValueError("isolation binary version mismatch")
    python_path = Path(toolchain["pythonPath"])
    if _digest(python_path) != toolchain["pythonSha256"]:
        raise ValueError("python binary digest mismatch")
    py_version = subprocess.run(
        [str(python_path), "-I", "-B", "--version"],
        capture_output=True,
        text=True,
        timeout=5,
        check=False,
        env={"PATH": "", "PYTHONDONTWRITEBYTECODE": "1"},
    )
    version_text = (py_version.stdout or py_version.stderr).strip()
    if py_version.returncode != 0 or version_text != toolchain["pythonVersion"]:
        raise ValueError("python version mismatch")
    stdlib = Path(toolchain["stdlibPath"])
    if (
        toolchain.get("stdlibMode") != "source-only-no-bytecode-v1"
        or toolchain.get("rejectSymlinks") is not True
    ):
        raise ValueError("python standard-library policy is not source-only and closed")
    if _tree_digest(stdlib) != toolchain["stdlibTreeSha256"]:
        raise ValueError("python standard-library closure digest mismatch")
    seen: set[str] = set()
    for item in toolchain["dynamicLibraries"]:
        path = Path(item["sourcePath"])
        if item["mountPath"] in seen or not path.is_absolute() or not Path(
            item["mountPath"]
        ).is_absolute():
            raise ValueError("dynamic-library closure is not exact")
        descriptor = _open_absolute_nofollow(
            path, directory=False, label="dynamic-library closure"
        )
        os.close(descriptor)
        if _digest(path) != item["sha256"]:
            raise ValueError("dynamic-library closure is not exact")
        seen.add(item["mountPath"])


_RESOURCE_LAUNCHER = b"""import os,resource,sys
limits=__import__('json').loads(os.environ['VAULTFIRE_RESOURCE_LIMITS'])
for name,value in (('RLIMIT_CPU',limits['cpuSeconds']),('RLIMIT_AS',limits['addressSpaceBytes']),('RLIMIT_FSIZE',limits['fileSizeBytes']),('RLIMIT_NOFILE',limits['openFileLimit']),('RLIMIT_NPROC',limits['childProcessLimit'])):
 resource.setrlimit(getattr(resource,name),(value,value))
os.execve('/runtime/bin/python',['/runtime/bin/python','-I','-B','/candidate/implementation.py','--request-jsonl','/input/requests.jsonl','--response-jsonl','/output/responses.jsonl'],dict(os.environ))
"""


def _sandbox_command(
    policy: dict, implementation: Path, request_path: Path, output_dir: Path
) -> tuple[list[str], list[str]]:
    isolation, toolchain = policy["isolation"], policy["toolchain"]
    command = [
        isolation["binaryPath"],
        "--unshare-all",
        "--die-with-parent",
        "--new-session",
        "--chdir",
        "/work",
        "--uid",
        "65534",
        "--gid",
        "65534",
        "--clearenv",
        "--dev",
        "/dev",
        "--dir",
        "/runtime",
        "--dir",
        "/work",
        "--dir",
        "/runtime/bin",
        "--dir",
        "/runtime/lib",
        "--ro-bind",
        toolchain["pythonPath"],
        "/runtime/bin/python",
        "--ro-bind",
        toolchain["stdlibPath"],
        "/runtime/lib/python3.14",
    ]
    created: set[str] = {"/runtime", "/runtime/bin", "/runtime/lib"}
    for item in toolchain["dynamicLibraries"]:
        parent = str(PurePosixPath(item["mountPath"]).parent)
        chain: list[str] = []
        while parent not in {"", "/"} and parent not in created:
            chain.append(parent)
            parent = str(PurePosixPath(parent).parent)
        for directory in reversed(chain):
            command += ["--dir", directory]
            created.add(directory)
        command += ["--ro-bind", item["sourcePath"], item["mountPath"]]
    command += [
        "--dir",
        "/candidate",
        "--dir",
        "/input",
        "--dir",
        "/output",
        "--ro-bind",
        str(implementation),
        "/candidate/implementation.py",
        "--ro-bind",
        str(request_path),
        "/input/requests.jsonl",
        "--bind",
        str(output_dir),
        "/output",
        "--ro-bind-data",
        str(len(_RESOURCE_LAUNCHER)),
        "/runtime/launcher.py",
        "--setenv",
        "PYTHONHOME",
        "/runtime",
        "--setenv",
        "PYTHONHASHSEED",
        "0",
        "--setenv",
        "PYTHONDONTWRITEBYTECODE",
        "1",
        "--setenv",
        "TZ",
        "UTC",
        "--setenv",
        "LC_ALL",
        "C.UTF-8",
        "--setenv",
        "PATH",
        "",
        "--setenv",
        "PWD",
        "/work",
        "--setenv",
        "VAULTFIRE_RESOURCE_LIMITS",
        json.dumps(
            {
                key: isolation[key]
                for key in (
                    "cpuSeconds",
                    "addressSpaceBytes",
                    "fileSizeBytes",
                    "openFileLimit",
                    "childProcessLimit",
                )
            },
            sort_keys=True,
            separators=(",", ":"),
        ),
        "--",
        "/runtime/bin/python",
        "-I",
        "-B",
        "/runtime/launcher.py",
    ]
    candidate_argv = [
        "/runtime/bin/python",
        "-I",
        "-B",
        "/candidate/implementation.py",
        "--request-jsonl",
        "/input/requests.jsonl",
        "--response-jsonl",
        "/output/responses.jsonl",
    ]
    return command, candidate_argv


def _run_isolated(
    policy: dict, implementation: Path, request_bytes: bytes
) -> tuple[bytes, dict]:
    """Execute one exact implementation under an enforced OS boundary.

    This internal primitive accepts a policy only so a temporary regression
    fixture can exercise the finite path.  The public API always calls
    ``_policy`` and therefore cannot supply or override a trust root.
    """
    _validate_exact_host_toolchain(policy)
    try:
        implementation_fd = _open_absolute_nofollow(
            implementation.absolute(),
            directory=False,
            label="canonical candidate implementation",
        )
    except (OSError, ValueError) as exc:
        raise ValueError(
            "canonical candidate implementation identity mismatch"
        ) from exc
    os.close(implementation_fd)
    if _digest(implementation) != policy["candidateImplementationSha256"]:
        raise ValueError("canonical candidate implementation identity mismatch")
    with tempfile.TemporaryDirectory() as temp_text:
        temp = Path(temp_text)
        request_path = temp / "requests.jsonl"
        output_dir = temp / "output"
        output_dir.mkdir()
        output_dir.chmod(0o777)
        request_path.write_bytes(request_bytes)
        command, candidate_argv = _sandbox_command(
            policy, implementation, request_path, output_dir
        )
        # Bubblewrap's --ro-bind-data consumes the next inherited descriptor.
        read_fd, write_fd = os.pipe()
        os.write(write_fd, _RESOURCE_LAUNCHER)
        os.close(write_fd)
        marker = str(read_fd)
        data_index = command.index(str(len(_RESOURCE_LAUNCHER)))
        command[data_index] = marker
        started_utc = dt.datetime.now(dt.timezone.utc)
        started_monotonic = time.monotonic_ns()
        try:
            process = subprocess.run(
                command,
                cwd="/",
                env={},
                capture_output=True,
                timeout=policy["isolation"]["wallClockSeconds"],
                check=False,
                pass_fds=(read_fd,),
            )
        finally:
            os.close(read_fd)
        # Revalidate all caller-independent runtime objects after execution.
        # Any rename/substitution that raced the launch invalidates the result,
        # even if the isolated process exited successfully.
        _validate_exact_host_toolchain(policy)
        if _digest(implementation) != policy["candidateImplementationSha256"]:
            raise ValueError(
                "canonical candidate implementation changed during execution"
            )
        ended_monotonic = time.monotonic_ns()
        ended_utc = dt.datetime.now(dt.timezone.utc)
        response_path = output_dir / "responses.jsonl"
        response = response_path.read_bytes() if response_path.is_file() else b""
        measurements = {
            "isolationArgv": command,
            "candidateArgv": candidate_argv,
            "startedAtUtc": started_utc.isoformat(timespec="microseconds").replace(
                "+00:00", "Z"
            ),
            "endedAtUtc": ended_utc.isoformat(timespec="microseconds").replace(
                "+00:00", "Z"
            ),
            "durationMonotonicNs": ended_monotonic - started_monotonic,
            "exitCode": process.returncode,
            "stdoutBase64": base64.b64encode(process.stdout).decode(),
            "stdoutSha256": hashlib.sha256(process.stdout).hexdigest(),
            "stderrBase64": base64.b64encode(process.stderr).decode(),
            "stderrSha256": hashlib.sha256(process.stderr).hexdigest(),
            "requestSha256": hashlib.sha256(request_bytes).hexdigest(),
            "responseSha256": hashlib.sha256(response).hexdigest(),
        }
        if (
            process.returncode != 0
            or process.stdout
            or process.stderr
            or not response
        ):
            raise ValueError(
                "candidate isolation failed closed: "
                + canonical(measurements).decode()
            )
        return response, measurements


def _independent_oracle(
    context: dict,
    chosen: list[dict],
    response_bytes: bytes,
    execution_test_id: str,
) -> bytes:
    responses: dict[str, bytes] = {}
    expected_ids = {
        row[side]["contentId"] for row in chosen for side in ("left", "right")
    }
    for line in response_bytes.decode("utf-8").splitlines():
        response = strict_object(line)
        if set(response) != {"requestId", "portabilityOutputBase64"}:
            raise ValueError(
                "candidate response may contain only requestId and opaque output"
            )
        request_id = response["requestId"]
        if request_id in responses or request_id not in expected_ids:
            raise ValueError("candidate response identity is duplicate or unexpected")
        try:
            raw = base64.b64decode(
                response["portabilityOutputBase64"], validate=True
            )
        except (ValueError, binascii.Error) as exc:
            raise ValueError("candidate response encoding invalid") from exc
        if not raw:
            raise ValueError("candidate response is empty")
        responses[request_id] = raw
    if set(responses) != expected_ids:
        raise ValueError("candidate response coverage mismatch")
    events: list[dict] = []
    for row in chosen:
        left_raw = responses[row["left"]["contentId"]]
        right_raw = responses[row["right"]["contentId"]]
        left_sha = hashlib.sha256(left_raw).hexdigest()
        right_sha = hashlib.sha256(right_raw).hexdigest()
        expected = _expected_relationship(row)
        event = {
            "pairId": row["pairId"],
            "expectedRelationship": expected,
            "observedRelationship": "linked" if left_sha == right_sha else "unlinked",
            "leftInputSha256": row["left"]["caseInputSha256"],
            "rightInputSha256": row["right"]["caseInputSha256"],
            "leftCandidateOutputBase64": base64.b64encode(left_raw).decode(),
            "rightCandidateOutputBase64": base64.b64encode(right_raw).decode(),
            "leftCandidateOutputSha256": left_sha,
            "rightCandidateOutputSha256": right_sha,
            "oracleId": INDEPENDENT_ORACLE_ID,
            "candidateDeclaredPredicates": False,
        }
        event["runnerOutputSha256"] = sha(
            DOMAIN_OUTPUT,
            {
                "context": context,
                "executionTestId": execution_test_id,
                "event": event,
            },
        )
        events.append(event)
    _relationship_verdict(events)
    return b"".join(canonical(event) + b"\n" for event in events)


def _git_blob(repo: Path, commit: str, rel_path: str) -> str:
    process = subprocess.run(
        ["git", "-C", str(repo), "rev-parse", f"{commit}:{rel_path}"],
        capture_output=True,
        text=True,
        timeout=10,
        check=False,
        env={"PATH": "/usr/bin:/bin", "LC_ALL": "C"},
    )
    value = process.stdout.strip()
    if process.returncode != 0 or COMMIT.fullmatch(value) is None:
        raise ValueError("candidate implementation is not a tracked blob at sourceCommit")
    return value


def _git_value(repo: Path, *arguments: str) -> str:
    process = subprocess.run(
        ["git", "-C", str(repo), *arguments],
        capture_output=True,
        text=True,
        timeout=10,
        check=False,
        env={"PATH": "/usr/bin:/bin", "LC_ALL": "C"},
    )
    if process.returncode != 0:
        raise ValueError("exact Git history binding is unavailable")
    return process.stdout.strip()


def _sign_record(record: dict, policy: dict) -> dict:
    signer = policy["executionSigner"]
    location = os.environ.get("VAULTFIRE_EXECUTION_SIGNING_KEY")
    if (
        type(location) is not str
        or hashlib.sha256(location.encode()).hexdigest()
        != signer["privateKeyLocationSha256"]
    ):
        raise ValueError("execution signing-key location is not independently pinned")
    try:
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric.ed25519 import (
            Ed25519PrivateKey,
        )
    except ImportError as exc:
        raise ValueError("Ed25519 execution signer is unavailable") from exc
    key_bytes = Path(location).read_bytes()
    key = serialization.load_pem_private_key(key_bytes, password=None)
    if not isinstance(key, Ed25519PrivateKey):
        raise ValueError("execution signing key is not Ed25519")
    public_raw = key.public_key().public_bytes(
        serialization.Encoding.Raw, serialization.PublicFormat.Raw
    )
    if (
        base64.b64encode(public_raw).decode() != signer["publicKeyBase64"]
        or hashlib.sha256(public_raw).hexdigest() != signer["publicKeySha256"]
    ):
        raise ValueError("execution signer does not match pinned public key")
    payload = DOMAIN_RECEIPT + canonical(record)
    return {
        "keyType": "Ed25519",
        "publicKeySha256": signer["publicKeySha256"],
        "signedPayloadSha256": hashlib.sha256(payload).hexdigest(),
        "signatureBase64": base64.b64encode(key.sign(payload)).decode(),
    }


def execute_candidate_protocol(
    context_path: str | Path,
    corpus_path: str | Path,
    selection_path: str | Path,
    test_id: str = "privacy.combined",
    candidate_adapter: str | None = None,
    output_path: str | None = None,
    execution_record_path: str | None = None,
    selection_commit: str | None = None,
    selection_tree: str | None = None,
) -> bytes:
    """Public fail-closed execution API.

    ``candidate_adapter`` exists only to turn legacy calls into an explicit
    rejection.  There is no supported implementation override.
    """
    if candidate_adapter is not None:
        raise ValueError("caller-selected candidate adapter paths are prohibited")
    if test_id not in TESTS | {"privacy.combined"}:
        raise ValueError("testId malformed")
    if (
        type(selection_commit) is not str
        or COMMIT.fullmatch(selection_commit) is None
        or type(selection_tree) is not str
        or COMMIT.fullmatch(selection_tree) is None
    ):
        raise ValueError("selection commit/tree binding is mandatory and malformed")
    repo = Path(__file__).resolve().parents[3]
    policy = _policy(repo)
    context = strict_object(wrapped_content(context_path, "test-command").decode())
    validate_context(context)
    if (
        _git_value(repo, "rev-parse", f"{selection_commit}^")
        != context["sourceCommit"]
        or _git_value(repo, "rev-parse", f"{selection_commit}^{{tree}}")
        != selection_tree
    ):
        raise ValueError(
            "selectionCommit must be the single direct child of sourceCommit "
            "with the exact declared tree"
        )
    if (
        context["executionPolicySha256"] != PINNED_POLICY_SHA256
        or context["candidateImplementationPath"]
        != policy["canonicalImplementationPath"]
        or context["candidateInterfaceId"] != policy["candidateInterfaceId"]
        or context["independentOracleId"] != policy["independentOracleId"]
    ):
        raise ValueError("execution context differs from pinned policy")
    universe_bytes = wrapped_content(corpus_path, "corpus-universe")
    selection_bytes = wrapped_content(selection_path, "deterministic-selection")
    if (
        hashlib.sha256(universe_bytes).hexdigest()
        != context["corpusUniverseSha256"]
        or hashlib.sha256(selection_bytes).hexdigest()
        != context["selectionManifestSha256"]
    ):
        raise ValueError("input digest mismatch")
    rows = [
        strict_object(line)
        for line in universe_bytes.decode().splitlines()
        if line
    ]
    selection = strict_object(selection_bytes.decode())
    if set(selection) != {
        "schemaVersion",
        "recordType",
        "seedOpeningBase64",
        "seedOpeningSha256",
        "orderedPairIds",
        "coverage",
    }:
        raise ValueError("selection manifest fields are not exact")
    seed = base64.b64decode(selection["seedOpeningBase64"], validate=True)
    expected = derive_selection(rows, seed)
    if (
        hashlib.sha256(seed).hexdigest() != selection["seedOpeningSha256"]
        or selection["seedOpeningSha256"] != context["seedOpeningSha256"]
        or selection["orderedPairIds"] != expected
        or selection["coverage"]
        != {test: SAMPLES_PER_TEST for test in sorted(TESTS)}
    ):
        raise ValueError("selection is not unbiased beacon-derived complete coverage")
    by_id = {row["pairId"]: row for row in rows}
    chosen = [
        by_id[pair_id]
        for pair_id in expected
        if test_id == "privacy.combined" or by_id[pair_id]["testId"] == test_id
    ]
    implementation = _canonical_regular_file(
        repo,
        context["candidateImplementationPath"],
        "canonical candidate implementation",
    )
    if (
        _digest(implementation) != context["candidateImplementationSha256"]
        or _git_blob(repo, context["sourceCommit"], context["candidateImplementationPath"])
        != context["candidateImplementationGitBlob"]
    ):
        raise ValueError("candidate bytes/blob are not exact at sourceCommit")
    requests_by_id: dict[str, dict] = {}
    for row in chosen:
        for side in ("left", "right"):
            item = row[side]
            requests_by_id[item["contentId"]] = {
                "requestId": item["contentId"],
                "candidateId": context["candidateId"],
                "moduleId": context["candidateModuleId"],
                "routeId": context["candidateRouteId"],
                "scopeSha256": context["scopeSha256"],
                "caseInputBase64": item["caseInputBase64"],
                "caseInputSha256": item["caseInputSha256"],
            }
    request_bytes = b"".join(
        canonical(requests_by_id[key]) + b"\n" for key in sorted(requests_by_id)
    )
    response_bytes, measurements = _run_isolated(
        {
            **policy,
            "candidateImplementationSha256": context[
                "candidateImplementationSha256"
            ],
        },
        implementation,
        request_bytes,
    )
    raw_events = _independent_oracle(context, chosen, response_bytes, test_id)
    if output_path is None or execution_record_path is None:
        raise ValueError("raw-events and execution-record paths are both mandatory")
    raw_target = _canonical_output(repo, output_path, ".jsonl")
    record_target = _canonical_output(repo, execution_record_path, ".json")
    if (
        raw_target.parent != record_target.parent
        or raw_target.name != "raw-events.jsonl"
        or record_target.name != "execution-record.json"
    ):
        raise ValueError(
            "execution outputs must name one canonical generation channel"
        )
    nonce = secrets.token_bytes(32)
    generation_id = "generation-" + sha(
        DOMAIN_GENERATION,
        {
            "candidateId": context["candidateId"],
            "sourceCommit": context["sourceCommit"],
            "selectionCommit": selection_commit,
            "rawEventsSha256": hashlib.sha256(raw_events).hexdigest(),
            "nonceSha256": hashlib.sha256(nonce).hexdigest(),
        },
    )
    generation_rel = (
        raw_target.parent.relative_to(repo)
        / "generations"
        / generation_id
    )
    raw_generation_rel = (generation_rel / "raw-events.jsonl").as_posix()
    record_generation_rel = (generation_rel / "execution-record.json").as_posix()
    pointer_rel = (raw_target.parent.relative_to(repo) / "CURRENT.json").as_posix()
    record = {
        "schemaVersion": "3.0.0",
        "recordType": "privacy-unlinkability-execution-output",
        "candidateId": context["candidateId"],
        "sourceCommit": context["sourceCommit"],
        "gitTree": context["gitTree"],
        "selectionCommit": selection_commit,
        "selectionTree": selection_tree,
        "scopeSha256": context["scopeSha256"],
        "chain": "base",
        "testId": test_id,
        "protocolId": context["protocolId"],
        "executionPolicySha256": context["executionPolicySha256"],
        "executablePath": RUNNER_REL,
        "executableSha256": context["executableSha256"],
        "candidateImplementationPath": context["candidateImplementationPath"],
        "candidateImplementationSha256": context[
            "candidateImplementationSha256"
        ],
        "candidateImplementationGitBlob": context[
            "candidateImplementationGitBlob"
        ],
        "candidateInterfaceId": context["candidateInterfaceId"],
        "independentOracleId": context["independentOracleId"],
        "launcherArgv": list(os.sys.argv[1:]),
        "isolationArgv": measurements["isolationArgv"],
        "candidateArgv": measurements["candidateArgv"],
        "startedAtUtc": measurements["startedAtUtc"],
        "endedAtUtc": measurements["endedAtUtc"],
        "durationMonotonicNs": measurements["durationMonotonicNs"],
        "exitCode": measurements["exitCode"],
        "stdoutBase64": measurements["stdoutBase64"],
        "stdoutSha256": measurements["stdoutSha256"],
        "stderrBase64": measurements["stderrBase64"],
        "stderrSha256": measurements["stderrSha256"],
        "requestSha256": measurements["requestSha256"],
        "responseBase64": base64.b64encode(response_bytes).decode(),
        "responseSha256": measurements["responseSha256"],
        "generationId": generation_id,
        "generationPointerPath": pointer_rel,
        "requestedRawEventsPath": output_path,
        "requestedExecutionRecordPath": execution_record_path,
        "rawEventsPath": raw_generation_rel,
        "rawEventsBase64": base64.b64encode(raw_events).decode(),
        "rawEventsSha256": hashlib.sha256(raw_events).hexdigest(),
        "eventCount": len(raw_events.splitlines()),
        "nonceBase64": base64.b64encode(nonce).decode(),
    }
    record["launcherSignature"] = _sign_record(record, policy)
    _atomic_generation(
        raw_target.parent,
        generation_id,
        raw_events,
        canonical(record) + b"\n",
        raw_generation_rel,
        record_generation_rel,
    )
    return raw_events


def _canonical_output(repo: Path, rel_text: str, suffix: str) -> Path:
    pure = PurePosixPath(rel_text)
    if (
        pure.is_absolute()
        or pure.as_posix() != rel_text
        or "\\" in rel_text
        or any(part in {"", ".", ".."} for part in pure.parts)
        or pure.suffix != suffix
        or not rel_text.startswith(
            "pr10/partner-package/evidence/organizational/privacy-outputs/"
        )
    ):
        raise ValueError("output path is not canonical package evidence")
    if repo.is_symlink() or not repo.is_dir():
        raise ValueError("repository output root is aliased or unavailable")
    root_stat = repo.stat()
    cursor_fd = os.open(repo, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    try:
        for part in pure.parts[:-1]:
            try:
                os.mkdir(part, 0o755, dir_fd=cursor_fd)
            except FileExistsError:
                pass
            next_fd = os.open(
                part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=cursor_fd
            )
            metadata = os.fstat(next_fd)
            if metadata.st_dev != root_stat.st_dev:
                os.close(next_fd)
                raise ValueError("output path crosses an untrusted mount boundary")
            os.close(cursor_fd)
            cursor_fd = next_fd
        try:
            metadata = os.stat(
                pure.name, dir_fd=cursor_fd, follow_symlinks=False
            )
        except FileNotFoundError:
            metadata = None
        if metadata is not None and (
            not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1
        ):
            raise ValueError("output path is an alias, symlink, or hardlink")
    finally:
        os.close(cursor_fd)
    target = repo.joinpath(*pure.parts)
    if not target.parent.resolve().is_relative_to(repo.resolve()):
        raise ValueError("output parent escaped the repository")
    if target.exists() and (target.is_symlink() or target.stat().st_nlink != 1):
        raise ValueError("output path is an alias, symlink, or hardlink")
    return target


def _atomic_generation(
    channel_root: Path,
    generation_id: str,
    raw_events: bytes,
    execution_record: bytes,
    raw_events_path: str,
    execution_record_path: str,
) -> None:
    if not re.fullmatch(r"generation-[0-9a-f]{64}", generation_id):
        raise ValueError("generation identity is malformed")
    absolute = channel_root.absolute()
    root_fd = _open_absolute_nofollow(
        absolute, directory=True, label="generation channel root"
    )
    opened = os.fstat(root_fd)
    expected_identity = (opened.st_dev, opened.st_ino)

    def require_attached() -> None:
        check_fd = _open_absolute_nofollow(
            absolute, directory=True, label="generation channel root"
        )
        try:
            check = os.fstat(check_fd)
            if (check.st_dev, check.st_ino) != expected_identity:
                raise ValueError(
                    "generation channel detached or replaced during publication"
                )
        finally:
            os.close(check_fd)

    def read_old_pointer() -> bytes | None:
        try:
            metadata = os.stat(
                "CURRENT.json", dir_fd=root_fd, follow_symlinks=False
            )
        except FileNotFoundError:
            return None
        if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1:
            raise ValueError("existing generation pointer is not a unique regular file")
        fd = os.open("CURRENT.json", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=root_fd)
        try:
            if (os.fstat(fd).st_dev, os.fstat(fd).st_ino) != (
                metadata.st_dev,
                metadata.st_ino,
            ):
                raise ValueError("existing generation pointer changed while opening")
            chunks: list[bytes] = []
            while True:
                chunk = os.read(fd, 64 * 1024)
                if not chunk:
                    return b"".join(chunks)
                chunks.append(chunk)
        finally:
            os.close(fd)

    def write_unique(name: str, content: bytes, parent_fd: int) -> tuple[int, int]:
        fd = os.open(
            name,
            os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
            0o600,
            dir_fd=parent_fd,
        )
        try:
            view = memoryview(content)
            while view:
                written = os.write(fd, view)
                if written <= 0:
                    raise OSError("short generation write")
                view = view[written:]
            os.fsync(fd)
            os.fchmod(fd, 0o400)
            metadata = os.fstat(fd)
            if (
                metadata.st_uid != os.geteuid()
                or metadata.st_nlink != 1
                or stat.S_IMODE(metadata.st_mode) != 0o400
            ):
                raise ValueError("published artifact ownership or mode is unsafe")
            os.fsync(fd)
            return metadata.st_dev, metadata.st_ino
        finally:
            os.close(fd)

    def remove_generation(parent_fd: int, name: str) -> None:
        try:
            generation_fd = os.open(
                name,
                os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
                dir_fd=parent_fd,
            )
        except OSError:
            return
        try:
            os.fchmod(generation_fd, 0o700)
            for child in ("raw-events.jsonl", "execution-record.json"):
                try:
                    os.unlink(child, dir_fd=generation_fd)
                except OSError:
                    pass
            os.fsync(generation_fd)
        finally:
            os.close(generation_fd)
        try:
            os.rmdir(name, dir_fd=parent_fd)
            os.fsync(parent_fd)
        except OSError:
            pass

    def restore_pointer(old: bytes | None) -> None:
        rollback = ".CURRENT-rollback-" + secrets.token_hex(16)
        try:
            if old is None:
                try:
                    os.unlink("CURRENT.json", dir_fd=root_fd)
                except FileNotFoundError:
                    pass
            else:
                write_unique(rollback, old, root_fd)
                os.rename(
                    rollback,
                    "CURRENT.json",
                    src_dir_fd=root_fd,
                    dst_dir_fd=root_fd,
                )
            os.fsync(root_fd)
        finally:
            try:
                os.unlink(rollback, dir_fd=root_fd)
            except OSError:
                pass

    staging = ".staging-" + secrets.token_hex(16)
    pointer_stage: str | None = None
    generations_fd = None
    published = False
    pointer_replaced = False
    old_pointer: bytes | None = None
    try:
        fcntl.flock(root_fd, fcntl.LOCK_EX)
        require_attached()
        old_pointer = read_old_pointer()
        try:
            os.mkdir("generations", 0o755, dir_fd=root_fd)
        except FileExistsError:
            pass
        require_attached()
        generations_fd = os.open(
            "generations",
            os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
            dir_fd=root_fd,
        )
        generations_metadata = os.fstat(generations_fd)
        if (
            generations_metadata.st_uid != os.geteuid()
            or generations_metadata.st_nlink < 2
        ):
            raise ValueError("generation parent ownership or link count is unsafe")
        os.mkdir(staging, 0o700, dir_fd=generations_fd)
        stage_fd = os.open(
            staging,
            os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
            dir_fd=generations_fd,
        )
        try:
            artifact_identities: dict[str, tuple[int, int]] = {}
            for name, content in (
                ("raw-events.jsonl", raw_events),
                ("execution-record.json", execution_record),
            ):
                artifact_identities[name] = write_unique(name, content, stage_fd)
            os.fchmod(stage_fd, 0o500)
            stage_metadata = os.fstat(stage_fd)
            if (
                stage_metadata.st_uid != os.geteuid()
                or stage_metadata.st_nlink != 2
                or stat.S_IMODE(stage_metadata.st_mode) != 0o500
            ):
                raise ValueError("generation directory ownership or mode is unsafe")
            os.fsync(stage_fd)
        finally:
            os.close(stage_fd)
        require_attached()
        os.rename(
            staging,
            generation_id,
            src_dir_fd=generations_fd,
            dst_dir_fd=generations_fd,
        )
        published = True
        os.fsync(generations_fd)
        generation_fd = os.open(
            generation_id,
            os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
            dir_fd=generations_fd,
        )
        try:
            generation_metadata = os.fstat(generation_fd)
            if (
                (generation_metadata.st_dev, generation_metadata.st_ino)
                != (stage_metadata.st_dev, stage_metadata.st_ino)
                or generation_metadata.st_uid != os.geteuid()
                or generation_metadata.st_nlink != 2
                or stat.S_IMODE(generation_metadata.st_mode) != 0o500
            ):
                raise ValueError("finalized generation identity or mode changed")
            for name, content in (
                ("raw-events.jsonl", raw_events),
                ("execution-record.json", execution_record),
            ):
                artifact_fd = os.open(
                    name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=generation_fd
                )
                try:
                    artifact = os.fstat(artifact_fd)
                    if (
                        (artifact.st_dev, artifact.st_ino) != artifact_identities[name]
                        or artifact.st_uid != os.geteuid()
                        or artifact.st_nlink != 1
                        or stat.S_IMODE(artifact.st_mode) != 0o400
                        or _fd_digest(artifact_fd)
                        != hashlib.sha256(content).hexdigest()
                    ):
                        raise ValueError("finalized generation artifact changed")
                finally:
                    os.close(artifact_fd)
            os.fsync(generation_fd)
        finally:
            os.close(generation_fd)
        require_attached()
        pointer = canonical(
            {
                "schemaVersion": "1.0.0",
                "recordType": "privacy-execution-generation-pointer",
                "generationId": generation_id,
                "rawEventsPath": raw_events_path,
                "rawEventsSha256": hashlib.sha256(raw_events).hexdigest(),
                "executionRecordPath": execution_record_path,
                "executionRecordSha256": hashlib.sha256(
                    execution_record
                ).hexdigest(),
            }
        ) + b"\n"
        pointer_stage = ".CURRENT-" + secrets.token_hex(16)
        write_unique(pointer_stage, pointer, root_fd)
        require_attached()
        os.rename(
            pointer_stage,
            "CURRENT.json",
            src_dir_fd=root_fd,
            dst_dir_fd=root_fd,
        )
        pointer_replaced = True
        pointer_stage = None
        os.fsync(root_fd)
        require_attached()
    except Exception:
        if pointer_replaced:
            restore_pointer(old_pointer)
        if published and generations_fd is not None:
            remove_generation(generations_fd, generation_id)
        raise
    finally:
        if pointer_stage is not None:
            try:
                os.unlink(pointer_stage, dir_fd=root_fd)
            except OSError:
                pass
        if generations_fd is not None:
            try:
                os.rmdir(staging, dir_fd=generations_fd)
            except OSError:
                pass
            os.close(generations_fd)
        try:
            fcntl.flock(root_fd, fcntl.LOCK_UN)
        except OSError:
            pass
        os.close(root_fd)


def _atomic_pair(
    first: Path, first_bytes: bytes, second: Path, second_bytes: bytes
) -> None:
    """Reject the obsolete split-file publication API.

    A two-rename interface cannot make two files transactionally visible.
    Callers must publish one immutable generation with ``_atomic_generation``.
    """
    raise ValueError("legacy split-file publication is prohibited")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--execute-candidate-protocol", action="store_true")
    parser.add_argument("--context")
    parser.add_argument("--corpus-universe")
    parser.add_argument("--selection")
    parser.add_argument("--selection-commit")
    parser.add_argument("--selection-tree")
    parser.add_argument("--raw-events")
    parser.add_argument("--execution-record")
    parser.add_argument("--test-id")
    args = parser.parse_args()
    if not all(
        (
            args.execute_candidate_protocol,
            args.context,
            args.corpus_universe,
            args.selection,
            args.selection_commit,
            args.selection_tree,
            args.raw_events,
            args.execution_record,
            args.test_id,
        )
    ):
        parser.error(
            "complete canonical context/corpus/selection/raw-events/"
            "execution-record arguments are required"
        )
    execute_candidate_protocol(
        args.context,
        args.corpus_universe,
        args.selection,
        args.test_id,
        None,
        args.raw_events,
        args.execution_record,
        args.selection_commit,
        args.selection_tree,
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
