#!/usr/bin/env python3
"""Acquire, authorize, deploy, inspect, and remove one connected release.

This practitioner driver joins the example's exact GitLab build evidence,
signed promotion contract, and disposable Docker runtime. Credentials are read
from named environment variables or a hidden prompt; their values never enter
arguments, journals, or receipts. Every remote or Docker write is attempted
once after a durable intent record. An interrupted write stops for explicit
reconciliation and is never retried automatically.

The driver is deliberately not an installer or release coordinator. Project,
membership, protected-environment, signing-key, and credential lifecycle remain
explicit administrative prerequisites.
"""
from __future__ import annotations

import argparse
import base64
import getpass
import hashlib
import io
import json
import os
from pathlib import Path
import re
import stat
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zipfile


EXAMPLE_DIRECTORY = Path(__file__).resolve().parent
DEPENDENCIES = {
    "release_tools.py": "20ba948029a62061240d4e1bb1aa813225c87d7ccc138208c2ccf7a02e22cd4f",
    "docker_runtime.py": "876803afe7478c6cdbf7b9f2a8d38cb864d4f01ad462bf9b6bcd6d67030133e3",
}
for _name, _expected in DEPENDENCIES.items():
    if hashlib.sha256((EXAMPLE_DIRECTORY / _name).read_bytes()).hexdigest() != _expected:
        raise RuntimeError(f"reviewed connected-release dependency differs: {_name}")

import docker_runtime  # noqa: E402
import release_tools  # noqa: E402


ALLOWED_ARCHIVE_FILES = {"dist/release.pyz", "dist/build-manifest.json"}
ALLOWED_ARCHIVE_MEMBERS = ALLOWED_ARCHIVE_FILES | {"dist/"}


class DriverError(RuntimeError):
    """Describe a non-secret contract, API, or reconciliation failure.

    Construction has no side effects. Messages may be written to stderr, but
    callers must not include credential values when raising this exception.
    """


def canonical(value: dict) -> bytes:
    """Serialize a JSON object deterministically for durable local receipts.

    The input must be JSON compatible. The function returns sorted compact
    UTF-8 JSON with one trailing newline and performs no I/O.
    """
    return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()


def write_new(path: Path, content: bytes, mode: int = 0o444) -> None:
    """Create and fsync one file without overwriting an earlier receipt.

    ``path`` must have an existing parent. Concurrent creation fails through
    ``O_EXCL``; errors propagate and no retry or replacement occurs.
    """
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
    with os.fdopen(descriptor, "wb") as stream:
        stream.write(content)
        stream.flush()
        os.fsync(stream.fileno())


def reserve(path: Path) -> None:
    """Reserve one output path before remote mutation without replacing it.

    The parent must already be a writable directory. The empty mode-0600 file
    proves exclusive ownership; a stopped run leaves it for reconciliation.
    """
    if not path.parent.is_dir() or not os.access(path.parent, os.W_OK):
        raise DriverError(f"output parent is not writable: {path.parent}")
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    os.close(descriptor)


def write_reserved(path: Path, content: bytes) -> None:
    """Fill one exclusively reserved empty receipt and fsync it once.

    A nonempty, symlinked, or broadly accessible path fails rather than being
    replaced. The caller serializes this single transition from empty to final.
    """
    if path.is_symlink() or path.stat().st_size != 0 or stat.S_IMODE(path.stat().st_mode) != 0o600:
        raise DriverError(f"reserved receipt identity differs: {path}")
    with path.open("wb") as stream:
        stream.write(content)
        stream.flush()
        os.fsync(stream.fileno())


class Journal:
    """Append fsynced, secret-free events to one new JSON Lines file.

    The path is created exclusively. Calls are sequential and append one event
    each; write failures propagate. This class does not redact arbitrary input,
    so callers provide only reviewed non-secret fields.
    """

    def __init__(self, path: Path):
        """Create a new journal path and refuse an existing run identity."""
        descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        self.stream = os.fdopen(descriptor, "ab", buffering=0)

    def event(self, kind: str, **values) -> dict:
        """Append one timestamped event and return the retained object."""
        item = {"kind": kind, "at": time.time(), **values}
        self.stream.write(canonical(item))
        os.fsync(self.stream.fileno())
        return item

    def close(self) -> None:
        """Close the journal descriptor; repeated close calls are harmless."""
        if not self.stream.closed:
            self.stream.close()


def credential(env_name: str, label: str) -> str:
    """Read one credential from a named environment variable or hidden prompt.

    Returns process-memory text and never logs it. Empty input raises before a
    request. Environment enumeration and persistence are intentionally absent.
    """
    value = os.environ.get(env_name) or getpass.getpass(f"{label}: ")
    if not value:
        raise DriverError(f"{label} is required")
    return value


class GitLab:
    """Issue bounded GitLab API calls while retaining write uncertainty.

    Reads and writes use one process-local token. Every mutation records intent
    before dispatch; transport failure is classified as outcome unknown and is
    never retried. Ordinary HTTP responses are journaled before validation.
    """

    def __init__(self, base_url: str, token: str, journal: Journal):
        """Bind one HTTPS API root, credential, and durable journal."""
        parsed = urllib.parse.urlparse(base_url)
        if (parsed.scheme, parsed.hostname, parsed.port, parsed.path, parsed.params,
                parsed.query, parsed.fragment) != ("https", "gitlab.com", None, "", "", "", ""):
            raise DriverError("this validated example currently supports only https://gitlab.com")
        self.api = "https://gitlab.com/api/v4"
        self.token, self.journal = token, journal

    def request(self, method: str, endpoint: str, payload=None, *, allowed=(200,), mutation=False,
                retained_response_fields=None):
        """Send one JSON request and return its status and parsed response.

        Payloads and responses are retained and therefore must contain no
        secrets. ``retained_response_fields`` limits a dictionary response in
        the journal while returning the complete response to the caller.
        Transport failure on a mutation is outcome unknown; callers reconcile
        its exact identity rather than replaying it.

        Args:
            method: HTTP method for the single request.
            endpoint: API-v4-relative endpoint without a leading slash.
            payload: Optional JSON-compatible request object.
            allowed: HTTP statuses the caller accepts as a completed result.
            mutation: Whether transport uncertainty must be classified as an
                outcome-unknown write.
            retained_response_fields: Optional dictionary keys to retain in
                the journal instead of the complete response.

        Returns:
            A pair containing the HTTP status and complete parsed response.

        Raises:
            DriverError: If transport fails, the response is disallowed, or a
                mutation outcome cannot be determined.

        Side effects:
            Performs one HTTPS request and appends fsynced journal events. A
            mutation receives one unique attempt ID and is never retried.
        """
        attempt = uuid.uuid4().hex if mutation else None
        self.journal.event("http_intent", method=method, endpoint=endpoint,
                           payload=payload, mutation=mutation, attempt_id=attempt)
        data = canonical(payload) if payload is not None else None
        headers = {"Authorization": f"Bearer {self.token}"}
        if data is not None:
            headers["Content-Type"] = "application/json"
        request = urllib.request.Request(f"{self.api}/{endpoint}", data=data,
                                         headers=headers, method=method)
        try:
            with urllib.request.build_opener(NoRedirect()).open(request, timeout=45) as response:
                status, raw = response.status, response.read()
        except urllib.error.HTTPError as error:
            status, raw = error.code, error.read()
        except Exception as error:
            self.journal.event("http_result", endpoint=endpoint, attempt_id=attempt,
                               outcome="outcome_unknown" if mutation else "transport_unknown",
                               exception_type=type(error).__name__)
            raise DriverError("GitLab response unknown; reconcile before replay") from None
        try:
            body = json.loads(raw) if raw else None
        except json.JSONDecodeError:
            body = {"non_json_response_bytes": len(raw)}
        retained = body
        if retained_response_fields is not None:
            retained = ({field: body.get(field) for field in retained_response_fields}
                        if isinstance(body, dict) else
                        {"response_type": type(body).__name__})
        self.journal.event("http_result", endpoint=endpoint, attempt_id=attempt,
                           status=status, response=retained)
        if status not in allowed:
            raise DriverError(f"GitLab returned HTTP {status} for {endpoint}")
        return status, body

    def require_user_id(self, expected_user_id: int, credential_label: str) -> int:
        """Bind this client's held credential to one expected GitLab user ID.

        Args:
            expected_user_id: Numeric user ID recorded during setup.
            credential_label: Non-secret role name used in journal evidence and
                failure text.

        Returns:
            The confirmed numeric user ID.

        Raises:
            DriverError: If authentication, transport, response shape, or user
                identity differs from the expected value.

        Side effects:
            Performs exactly one ``GET /user`` request and appends journal
            events retaining only the returned ID and the successful check.

        Notes:
            The check is deterministic for the credential held by this client;
            callers run it before any resource read or remote/Docker mutation.
        """
        if (not isinstance(expected_user_id, int) or isinstance(expected_user_id, bool) or
                expected_user_id <= 0):
            raise DriverError(f"expected {credential_label} user ID must be a positive integer")
        _, identity = self.request("GET", "user", retained_response_fields=("id",))
        observed_user_id = identity.get("id") if isinstance(identity, dict) else None
        if (not isinstance(observed_user_id, int) or isinstance(observed_user_id, bool) or
                observed_user_id != expected_user_id):
            raise DriverError(f"{credential_label} credential user ID differs")
        self.journal.event("credential_identity_confirmed", credential=credential_label,
                           user_id=observed_user_id)
        return observed_user_id

    def pages(self, endpoint: str) -> list:
        """Read at most 20 pages of one list endpoint without mutation."""
        values = []
        separator = "&" if "?" in endpoint else "?"
        for page in range(1, 21):
            _, batch = self.request("GET", f"{endpoint}{separator}per_page=100&page={page}")
            if not isinstance(batch, list):
                raise DriverError("paginated response is not a list")
            values.extend(batch)
            if len(batch) < 100:
                return values
        raise DriverError("pagination exceeded the fixed bound")

    def artifact_archive(self, project_id: int, job_id: int) -> bytes:
        """Download one exact job archive through at most one safe redirect.

        The initial request carries the token. A single HTTPS redirect is
        followed without the token and only its hostname is journaled, avoiding
        retention of signed query parameters. Transport failures stop without
        retry; archives are bounded to eight MiB.
        """
        endpoint = f"projects/{project_id}/jobs/{job_id}/artifacts"
        request = urllib.request.Request(f"{self.api}/{endpoint}",
                                         headers={"Authorization": f"Bearer {self.token}"})
        opener = urllib.request.build_opener(NoRedirect())
        self.journal.event("artifact_intent", endpoint=endpoint)
        try:
            try:
                with opener.open(request, timeout=45) as response:
                    status, raw = response.status, response.read(8 * 1024 * 1024 + 1)
            except urllib.error.HTTPError as error:
                if error.code not in (301, 302, 303, 307, 308) or not error.headers.get("Location"):
                    status, raw = error.code, error.read(4096)
                else:
                    location = error.headers["Location"]
                    parsed = urllib.parse.urlparse(location)
                    if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
                        raise DriverError("artifact redirect authority is unsafe")
                    self.journal.event("artifact_redirect", status=error.code, host=parsed.hostname)
                    redirected = urllib.request.Request(location)
                    with opener.open(redirected, timeout=45) as response:
                        status, raw = response.status, response.read(8 * 1024 * 1024 + 1)
        except DriverError:
            raise
        except Exception as error:
            self.journal.event("artifact_result", outcome="transport_unknown",
                               exception_type=type(error).__name__)
            raise DriverError("artifact response unknown; do not retry blindly") from None
        self.journal.event("artifact_result", status=status, bytes=len(raw),
                           sha256=hashlib.sha256(raw).hexdigest())
        if status != 200 or len(raw) > 8 * 1024 * 1024:
            raise DriverError("artifact archive response differs or exceeds bound")
        return raw


class NoRedirect(urllib.request.HTTPRedirectHandler):
    """Expose redirects for explicit one-hop, credential-safe handling."""

    def redirect_request(self, request, fp, code, message, headers, new_url):
        """Return ``None`` so urllib surfaces the redirect as HTTPError."""
        return None


def require_sha(value: str) -> str:
    """Require a full lowercase Git SHA-1 and return it unchanged."""
    if not re.fullmatch(r"[0-9a-f]{40}", value):
        raise DriverError("source SHA must be 40 lowercase hexadecimal characters")
    return value


def immutable_directory(path: Path) -> None:
    """Create one new operator directory with mode 0700 and no replacement."""
    path.mkdir(parents=True, mode=0o700, exist_ok=False)
    path.chmod(0o700)


def extract_archive(raw: bytes, directory: Path) -> tuple[Path, Path, Path]:
    """Retain an archive and safely extract its two exact regular files.

    Traversal, symlinks, encryption, duplicates, extra entries, and oversized
    members fail before use. Outputs are created 0444 without replacement.
    """
    archive = directory / "job-artifacts.zip"
    write_new(archive, raw)
    with zipfile.ZipFile(io.BytesIO(raw)) as bundle:
        members, names = bundle.infolist(), [item.filename for item in bundle.infolist()]
        if (set(names) - ALLOWED_ARCHIVE_MEMBERS or len(names) != len(set(names)) or
                {item.filename for item in members if not item.is_dir()} != ALLOWED_ARCHIVE_FILES):
            raise DriverError("artifact archive inventory differs")
        for item in members:
            if item.is_dir():
                if item.filename != "dist/":
                    raise DriverError("artifact directory differs")
                continue
            if (item.flag_bits & 1 or item.file_size > 4 * 1024 * 1024 or
                    Path(item.filename).is_absolute() or ".." in Path(item.filename).parts or
                    stat.S_ISLNK(item.external_attr >> 16)):
                raise DriverError("artifact member is unsafe")
            write_new(directory / Path(item.filename).name, bundle.read(item))
    return archive, directory / "release.pyz", directory / "build-manifest.json"


def expected_namespace(record: dict) -> argparse.Namespace:
    """Convert one acquired receipt into release_tools' exact input contract."""
    paths = record["paths"]
    return argparse.Namespace(
        project_id=record["project"]["id"], project_path=record["project"]["path"],
        source_sha=record["source_sha"], pipeline_id=record["pipeline"]["id"],
        pipeline_source=record["pipeline"]["source"], ref=record["pipeline"]["ref"],
        job_id=record["job"]["id"], job_name=record["job"]["name"],
        runner_id=record["runner"]["id"], version=record["version"],
        builder=Path(paths["builder"]), ci_file=Path(paths["ci"]),
        version_file=Path(paths["version"]), artifact=Path(paths["artifact"]),
    )


def acquire(args, journal: Journal) -> dict:
    """Acquire and validate one exact successful GitLab build.

    Confirms the exact Owner and operator user IDs before creating acquisition
    output or reading release resources. Then creates a new 0700 directory
    containing the full archive, two extracted files, three exact source blobs,
    and a canonical operator receipt. Owner authority reads project/runner
    configuration; operator authority reads the job, pipeline, source, and
    artifact. Any mismatch leaves secret-free journal evidence and raises
    without remote mutation or retry.

    Args:
        args: Parsed acquisition contract, including positive expected Owner
            and operator IDs, build identity, credential sources, and output.
        journal: Exclusive journal receiving non-secret request evidence.

    Returns:
        Paths and the verified artifact digest for the acquired build.

    Raises:
        DriverError: If credential identity, GitLab resources, source, runner,
            manifest, or artifact differs from the supplied contract.
        OSError: If exclusive output creation or durable writes fail.

    Side effects:
        Prompts for missing credentials, performs bounded GitLab reads, creates
        one output directory, and writes immutable acquisition evidence.

    Notes:
        The operation performs no remote mutation and is not concurrency safe
        for a shared output path; exclusive creation rejects competing runs.
    """
    source_sha = require_sha(args.source_sha)
    operator_token = credential(args.operator_token_env, "operator token")
    owner_token = (credential(args.owner_token_env, "Owner token")
                   if args.owner_token_env else operator_token)
    operator = GitLab(args.gitlab_url, operator_token, journal)
    owner = GitLab(args.gitlab_url, owner_token, journal)
    operator_user_id = operator.require_user_id(args.operator_id, "operator")
    owner_user_id = owner.require_user_id(args.owner_id, "Owner")
    immutable_directory(args.output_dir)
    _, project = owner.request("GET", f"projects/{args.project_id}")
    _, job = operator.request("GET", f"projects/{args.project_id}/jobs/{args.job_id}")
    _, pipeline = operator.request("GET", f"projects/{args.project_id}/pipelines/{args.pipeline_id}")
    runner_id = (job.get("runner") or {}).get("id")
    _, runner = owner.request("GET", f"runners/{runner_id}")
    artifact_file = job.get("artifacts_file") or {}
    if (project.get("id") != args.project_id or project.get("path_with_namespace") != args.project_path or
            project.get("visibility") != "private" or
            job.get("id") != args.job_id or job.get("name") != args.job_name or
            job.get("status") != "success" or (job.get("commit") or {}).get("id") != source_sha or
            (job.get("pipeline") or {}).get("id") != args.pipeline_id or
            not artifact_file.get("filename") or not isinstance(artifact_file.get("size"), int) or
            artifact_file.get("size", 0) <= 0 or
            pipeline.get("id") != args.pipeline_id or pipeline.get("sha") != source_sha or
            pipeline.get("status") != "success" or pipeline.get("source") != "push" or
            pipeline.get("ref") != project.get("default_branch") or
            runner.get("id") != runner_id or runner.get("runner_type") != "instance_type" or
            args.runner_tag not in runner.get("tag_list", [])):
        raise DriverError("GitLab build identity or runner differs")
    manager = job.get("runner_manager") or {}
    if manager.get("platform") != "linux" or manager.get("architecture") != "amd64":
        raise DriverError("observed build platform differs")
    sources = {}
    for name, local_name in (("build_fixture.py", "build_fixture.py"),
                             (".gitlab-ci.yml", "gitlab-ci.yml"),
                             ("version.txt", "version.txt")):
        encoded = urllib.parse.quote(name, safe="")
        _, body = operator.request("GET", f"projects/{args.project_id}/repository/files/{encoded}?ref={source_sha}")
        if (body.get("file_path") != name or body.get("commit_id") != source_sha or
                body.get("ref") != source_sha or body.get("encoding") != "base64"):
            raise DriverError(f"source response identity differs: {name}")
        path = args.output_dir / local_name
        write_new(path, base64.b64decode(body["content"], validate=True))
        sources[name] = path
    archive, artifact, manifest_path = extract_archive(
        operator.artifact_archive(args.project_id, args.job_id), args.output_dir)
    record = {
        "schema": "gss-connected-release-inputs-v1",
        "project": {"id": args.project_id, "path": args.project_path},
        "credential_identities": {"owner_user_id": owner_user_id,
                                  "operator_user_id": operator_user_id},
        "source_sha": source_sha,
        "pipeline": {"id": args.pipeline_id, "source": "push", "ref": pipeline["ref"]},
        "job": {"id": args.job_id, "name": args.job_name},
        "runner": {"id": runner_id, "tag": args.runner_tag,
                   "manager_platform": "linux", "manager_architecture": "amd64"},
        "version": args.version,
        "paths": {"archive": str(archive.resolve()), "artifact": str(artifact.resolve()),
                  "manifest": str(manifest_path.resolve()),
                  "builder": str(sources["build_fixture.py"].resolve()),
                  "ci": str(sources[".gitlab-ci.yml"].resolve()),
                  "version": str(sources["version.txt"].resolve())},
    }
    manifest, _ = release_tools.load_object(manifest_path)
    release_tools.validate_manifest(manifest, artifact, expected_namespace(record))
    record["artifact_sha256"] = release_tools.sha256(artifact)
    output = args.output_dir / "operator-inputs.json"
    write_new(output, canonical(record))
    journal.event("acquire_complete", inputs=str(output), artifact_sha256=record["artifact_sha256"])
    return {"inputs": str(output), "artifact_sha256": record["artifact_sha256"]}


def load_inputs(path: Path) -> dict:
    """Load canonical acquired inputs and revalidate every local build byte."""
    record, _ = release_tools.load_object(path)
    if record.get("schema") != "gss-connected-release-inputs-v1":
        raise DriverError("operator inputs schema differs")
    manifest, _ = release_tools.load_object(Path(record["paths"]["manifest"]))
    release_tools.validate_manifest(manifest, Path(record["paths"]["artifact"]),
                                    expected_namespace(record))
    return record


def verify_promotion(args, record: dict) -> dict:
    """Run the public promotion verifier against freshly validated inputs."""
    expected = vars(expected_namespace(record))
    expected.update(command="verify", manifest=Path(record["paths"]["manifest"]),
                    artifact=Path(record["paths"]["artifact"]), attestation=args.attestation,
                    signature=args.signature, public_key=args.public_key,
                    trusted_fingerprint=args.trusted_fingerprint, release_id=args.release_id)
    return release_tools.run(argparse.Namespace(**expected))


def deploy(args, journal: Journal) -> dict:
    """Verify, create a running deployment, prove Docker, and mark success.

    The held operator credential is confirmed against the required user ID
    before verification, output reservation, or mutation. Verification occurs
    immediately before GitLab and Docker mutation. The exact container receipt
    is persisted immediately after creation. A failure leaves the running
    deployment/container identity in the journal for manual reconciliation;
    neither write is automatically retried or relabelled.

    Args:
        args: Parsed signed-release inputs, expected operator ID, GitLab and
            Docker targets, credential source, and exclusive receipt path.
        journal: Exclusive journal receiving non-secret operation evidence.

    Returns:
        The successful GitLab deployment, Docker proof, promotion result, and
        durable receipt path.

    Raises:
        DriverError: If credential identity, release verification, deployment,
            runtime proof, or readback differs from the exact contract.
        OSError: If receipt reservation or durable evidence writes fail.

    Side effects:
        Prompts for a credential, reads and mutates GitLab, reserves local
        receipts, and starts and verifies one Docker container.

    Notes:
        Remote and Docker mutations are single-attempt operations. Interrupted
        results require reconciliation from the recorded attempt identities.
    """
    operator_token = credential(args.operator_token_env, "operator token")
    api = GitLab(args.gitlab_url, operator_token, journal)
    api.require_user_id(args.operator_id, "operator")
    record = load_inputs(args.inputs)
    if args.environment != release_tools.TARGET:
        raise DriverError(f"environment must match signed target {release_tools.TARGET}")
    if not re.fullmatch(r"[a-z][a-z0-9-]{0,30}", args.release_id):
        raise DriverError("release ID must be a lowercase Docker-safe label")
    deployment_checkpoint = args.receipt.with_name(args.receipt.name + ".deployment.json")
    reserve(deployment_checkpoint)
    try:
        reserve(args.receipt)
    except Exception:
        if (not deployment_checkpoint.is_symlink() and deployment_checkpoint.is_file() and
                deployment_checkpoint.stat().st_size == 0):
            deployment_checkpoint.unlink()
        raise
    verified = verify_promotion(args, record)
    journal.event("promotion_verified_immediately_before_deployment", result=verified)
    payload = {"environment": args.environment, "sha": record["source_sha"],
               "ref": record["pipeline"]["ref"], "status": "running", "tag": False}
    _, deployment = api.request("POST", f"projects/{record['project']['id']}/deployments",
                                payload, allowed=(201,), mutation=True)
    if (not isinstance(deployment.get("id"), int) or deployment.get("sha") != record["source_sha"] or
            deployment.get("ref") != record["pipeline"]["ref"] or deployment.get("status") != "running" or
            deployment.get("deployable") is not None or
            (deployment.get("environment") or {}).get("name") != args.environment):
        raise DriverError("running deployment response differs")
    write_reserved(deployment_checkpoint, canonical({
        "schema": "gss-connected-deployment-checkpoint-v1",
        "project_id": record["project"]["id"], "source_sha": record["source_sha"],
        "environment": args.environment, "deployment": deployment,
    }))
    journal.event("deployment_checkpoint_written", path=str(deployment_checkpoint),
                  deployment_id=deployment["id"])
    runtime = docker_runtime.DockerRuntime(journal.event, uuid.uuid4().hex, args.docker_context)
    verified = verify_promotion(args, record)
    journal.event("promotion_reverified_before_runtime", result=verified)
    receipt = runtime.start(Path(record["paths"]["artifact"]), verified["artifact_sha256"],
                            record["version"], args.release_id)
    durable = {"schema": "gss-connected-runtime-receipt-v1", "project_id": record["project"]["id"],
               "source_sha": record["source_sha"], "environment": args.environment,
               "deployment": deployment, "runtime": receipt}
    write_reserved(args.receipt, canonical(durable))
    proof = runtime.verify(receipt)
    _, terminal = api.request("PUT",
        f"projects/{record['project']['id']}/deployments/{deployment['id']}",
        {"status": "success"}, mutation=True)
    _, readback = api.request("GET", f"projects/{record['project']['id']}/deployments/{deployment['id']}")
    if (terminal.get("id") != deployment["id"] or readback.get("id") != deployment["id"] or
            readback.get("status") != "success" or readback.get("sha") != record["source_sha"] or
            readback.get("ref") != record["pipeline"]["ref"] or readback.get("deployable") is not None or
            (readback.get("environment") or {}).get("name") != args.environment):
        raise DriverError("successful deployment readback differs")
    result = {"outcome": "deployed", "receipt": str(args.receipt), "deployment": readback,
              "runtime_proof": proof, "promotion": verified}
    journal.event("deploy_complete", result=result)
    return result


def load_runtime(path: Path) -> dict:
    """Load one canonical exact runtime receipt without changing Docker."""
    value, _ = release_tools.load_object(path)
    if value.get("schema") != "gss-connected-runtime-receipt-v1":
        raise DriverError("runtime receipt schema differs")
    return value


def inspect_runtime(args, journal: Journal) -> dict:
    """Verify one exact recorded container and return its runtime proof."""
    value = load_runtime(args.receipt)
    runtime = docker_runtime.DockerRuntime(journal.event, value["runtime"]["run_id"], args.docker_context)
    proof = runtime.verify(value["runtime"])
    journal.event("runtime_inspection_complete", proof=proof)
    return proof


def remove_runtime(args, journal: Journal) -> dict:
    """Remove one exact recorded container after enforcing receipt ownership."""
    value = load_runtime(args.receipt)
    runtime = docker_runtime.DockerRuntime(journal.event, value["runtime"]["run_id"], args.docker_context)
    runtime.remove(value["runtime"])
    result = {"outcome": "removed", "container_id": value["runtime"]["container_id"]}
    journal.event("runtime_removal_complete", result=result)
    return result


def deny_deployment(args, journal: Journal) -> dict:
    """Prove one actor cannot create a deployment despite valid authentication.

    The same token reads its identity and project before the POST and reads its
    identity afterward. Only HTTP 401 or 403 with unchanged deployment IDs is
    classified as an operation-specific denial. No update denial is claimed.
    """
    api = GitLab(args.gitlab_url, credential(args.actor_token_env, "actor token"), journal)
    before = api.pages(f"projects/{args.project_id}/deployments")
    _, identity = api.request("GET", "user")
    _, project = api.request("GET", f"projects/{args.project_id}")
    if identity.get("id") != args.actor_id or project.get("id") != args.project_id:
        raise DriverError("actor positive control differs")
    status, _ = api.request("POST", f"projects/{args.project_id}/deployments",
        {"environment": args.environment, "sha": require_sha(args.source_sha), "ref": args.ref,
         "status": "running", "tag": False}, allowed=(401, 403), mutation=True)
    _, again = api.request("GET", "user")
    after = api.pages(f"projects/{args.project_id}/deployments")
    if again.get("id") != args.actor_id or [x.get("id") for x in before] != [x.get("id") for x in after]:
        raise DriverError("actor denial controls or deployment inventory differ")
    result = {"outcome": "denied", "http_status": status, "actor_id": args.actor_id,
              "deployment_ids_unchanged": [x.get("id") for x in after]}
    journal.event("deployment_denial_complete", result=result)
    return result


def stop_environment(args, journal: Journal) -> dict:
    """Stop one exact environment using the confirmed operator credential.

    The held credential must match ``operator_id`` before the environment read
    or stop request. The method then binds the supplied environment ID and name,
    sends one stop mutation, and requires the exact stopped readback. API and
    transport failures propagate; mutations are never retried automatically.

    Args:
        args: Parsed expected operator, project, and environment identities plus
            the process credential source.
        journal: Exclusive journal receiving non-secret operation evidence.

    Returns:
        The exact environment object read back in the stopped state.

    Raises:
        DriverError: If credential identity, environment identity, mutation, or
            terminal readback differs or has an unknown result.

    Side effects:
        Prompts for a credential, performs GitLab reads, sends one environment
        stop request, and appends durable journal evidence.

    Notes:
        The mutation is never retried automatically; an unknown result must be
        reconciled against the same environment ID.
    """
    api = GitLab(args.gitlab_url, credential(args.operator_token_env, "operator token"), journal)
    api.require_user_id(args.operator_id, "operator")
    _, before = api.request("GET", f"projects/{args.project_id}/environments/{args.environment_id}")
    if before.get("id") != args.environment_id or before.get("name") != args.environment:
        raise DriverError("environment identity differs before stop")
    api.request("POST", f"projects/{args.project_id}/environments/{args.environment_id}/stop",
                mutation=True)
    _, environment = api.request("GET", f"projects/{args.project_id}/environments/{args.environment_id}")
    if (environment.get("id") != args.environment_id or environment.get("name") != args.environment or
            environment.get("state") != "stopped"):
        raise DriverError("environment stop readback differs")
    journal.event("environment_stop_complete", environment=environment)
    return environment


def parser() -> argparse.ArgumentParser:
    """Build the side-effect-free CLI parser for the six public operations."""
    root = argparse.ArgumentParser(description=__doc__)
    root.add_argument("--gitlab-url", default="https://gitlab.com")
    commands = root.add_subparsers(dest="command", required=True)
    acquire_parser = commands.add_parser("acquire")
    for flag in ("project-id", "pipeline-id", "job-id", "owner-id", "operator-id"):
        acquire_parser.add_argument(f"--{flag}", type=int, required=True)
    for flag in ("project-path", "source-sha", "job-name", "version"):
        acquire_parser.add_argument(f"--{flag}", required=True)
    acquire_parser.add_argument("--runner-tag", default="saas-linux-small-amd64")
    acquire_parser.add_argument("--output-dir", type=Path, required=True)
    acquire_parser.add_argument("--owner-token-env",
                                help="optional separate Owner token variable; defaults to operator token")
    acquire_parser.add_argument("--operator-token-env", default="GSS_OPERATOR_TOKEN")
    deploy_parser = commands.add_parser("deploy")
    deploy_parser.add_argument("--operator-id", type=int, required=True)
    deploy_parser.add_argument("--inputs", type=Path, required=True)
    for flag in ("attestation", "signature", "public-key", "receipt"):
        deploy_parser.add_argument(f"--{flag}", type=Path, required=True)
    for flag in ("trusted-fingerprint", "release-id", "environment"):
        deploy_parser.add_argument(f"--{flag}", required=True)
    deploy_parser.add_argument("--operator-token-env", default="GSS_OPERATOR_TOKEN")
    deploy_parser.add_argument("--docker-context", default="desktop-linux")
    for name in ("inspect-runtime", "remove-runtime"):
        child = commands.add_parser(name)
        child.add_argument("--receipt", type=Path, required=True)
        child.add_argument("--docker-context", default="desktop-linux")
    denial = commands.add_parser("deny-deployment")
    denial.add_argument("--project-id", type=int, required=True)
    denial.add_argument("--actor-id", type=int, required=True)
    for flag in ("source-sha", "ref", "environment"):
        denial.add_argument(f"--{flag}", required=True)
    denial.add_argument("--actor-token-env", default="GSS_APPLICATION_TOKEN")
    stop = commands.add_parser("stop-environment")
    stop.add_argument("--project-id", type=int, required=True)
    stop.add_argument("--environment-id", type=int, required=True)
    stop.add_argument("--operator-id", type=int, required=True)
    stop.add_argument("--environment", required=True)
    stop.add_argument("--operator-token-env", default="GSS_OPERATOR_TOKEN")
    for command in commands.choices.values():
        command.add_argument("--journal", type=Path, required=True)
    return root


def main() -> None:
    """Parse one command, run it once, and print its non-secret JSON result."""
    args = parser().parse_args()
    journal = Journal(args.journal)
    try:
        operation = {"acquire": acquire, "deploy": deploy,
                     "inspect-runtime": inspect_runtime, "remove-runtime": remove_runtime,
                     "deny-deployment": deny_deployment, "stop-environment": stop_environment}[args.command]
        print(json.dumps(operation(args, journal), sort_keys=True))
    except Exception as error:
        journal.event("command_stopped", command=args.command,
                      exception_type=type(error).__name__, exception=str(error))
        raise
    finally:
        journal.close()


if __name__ == "__main__":
    main()
