#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""End-to-end milestone-8 smoke runner.

Two modes:

- ``ORCHESTRATOR_MODE=scripted`` (default): the full pipeline runs with the
  deterministic in-process client. No network, no real spend; the durable spend
  ledger still accounts a small synthetic cost. Use this to prove the wiring,
  the cap arithmetic, and the stop conditions.
- ``ORCHESTRATOR_MODE=real``: the same pipeline runs against an
  OpenAI-compatible chat-completions endpoint using a provider credential read
  from the environment. The client declares its per-call token ceilings and
  prices usage from frozen per-million-token rates, so the run is bounded by the
  per-attempt commitment and the experiment-wide owner cap.

It is fully automated once the environment is set: there are no interactive
prompts. Human decisions happen *before* the run (the owner authorisation and
the cap) and *after* it (review, revocation); a stop condition aborts the run
rather than asking a question.

Honest scope note: the frozen target's deterministic commands are fixed, so a
"real" run is a transport, pricing, and accounting smoke test. It is **not** a
measurement of model coding capability, and its metrics must not be reported as
one (docs/report-milestone8-readiness.md, "stay honest").

Environment
-----------
Required:
  ORCHESTRATOR_OWNER            owner name recorded in the authorisation
  ORCHESTRATOR_CAP              monetary cap in COST_UNITS (float > 0)

Common (defaults in brackets):
  ORCHESTRATOR_MODE             scripted | real            [scripted]
  ORCHESTRATOR_WORKDIR          experiment directory       [./smoke-run]
  ORCHESTRATOR_AUTHORIZED_AT    ISO-8601 timestamp         [now UTC]
  ORCHESTRATOR_AUTH_METHOD      decision method id         [owner-decision]
  ORCHESTRATOR_APPROVAL_REF     ticket/commit reference    [empty]
  ORCHESTRATOR_SEED             single trial seed          [1001]
  ORCHESTRATOR_SEEDS            comma list, overrides SEED  [unset] (all arms x seeds)
  ORCHESTRATOR_MODEL_COST       per-run budget (root)      [100.0]
  ORCHESTRATOR_PER_ATTEMPT_COMMITMENT  per-attempt cap     [5.0]
  ORCHESTRATOR_MAX_MODEL_CALLS  run limit                  [4]
  ORCHESTRATOR_MAX_ACTIONS      run limit                  [8]
  ORCHESTRATOR_MAX_NODES        run limit                  [8]
  ORCHESTRATOR_MAX_DEPTH        run limit                  [3]
  ORCHESTRATOR_MAX_INPUT_TOKENS per-call declared input cap [4000]
  ORCHESTRATOR_MAX_OUTPUT_TOKENS per-call declared output cap [1024]
  ORCHESTRATOR_RUN_MAX_INPUT_TOKENS run aggregate ceiling  [32768]
  ORCHESTRATOR_RUN_MAX_OUTPUT_TOKENS run aggregate ceiling [8192]
  ORCHESTRATOR_WALL_SECONDS     attempt wall clock         [120]
  ORCHESTRATOR_REQUIRE_CONFORMANCE  1 | 0                  [1]

Real mode only:
  ORCHESTRATOR_CONFIRM_REAL     must be exactly "yes"
  ORCHESTRATOR_PROVIDER_BASE_URL      e.g. https://api.example.com
  ORCHESTRATOR_PROVIDER_PATH          [/v1/chat/completions]
  ORCHESTRATOR_PROVIDER_MODEL         provider model id
  ORCHESTRATOR_PROVIDER_MODEL_VERSION [1]
  ORCHESTRATOR_PROVIDER_API_KEY       the secret (never logged)
  ORCHESTRATOR_PRICE_INPUT_PER_MTOK   price per 1M input tokens
  ORCHESTRATOR_PRICE_OUTPUT_PER_MTOK  price per 1M output tokens
  ORCHESTRATOR_PROVIDER_UNITS         [USD]  (catalogued: USD, COST_UNITS)
  ORCHESTRATOR_PROVIDER_TIMEOUT       seconds               [60]
  ORCHESTRATOR_CREDENTIAL_TTL_SECONDS credential lifetime   [3600]
  ORCHESTRATOR_REVOKE_URL             optional POST to revoke the credential
  ORCHESTRATOR_MAX_REPLY_BYTES        hard cap on a provider reply [1048576]
  ORCHESTRATOR_MAX_RATE_LIMIT_RETRIES bounded 429 retries per call   [2]
  ORCHESTRATOR_RATE_LIMIT_BACKOFF     base backoff seconds (doubles) [0.5]
  ORCHESTRATOR_DEBUG_TRANSCRIPT       off by default; "1" writes a bounded,
                                      redacted prompt/reply transcript to
                                      <workdir>/debug/transcript.jsonl (0600),
                                      or set an explicit path

Recommended order for a first real test: run the scripted mode, then
``--probe`` in real mode (exactly one billable call), then the full four-arm
run.

Commands: ``python scripts/smoke_run.py``, ``--probe``, ``--inspect``,
``--resume``.

Exit status: 0 success; 1 refused configuration or refused entry (validation
failure, or the workdir is locked by another ``run``/``--resume``); 2 run
limit or budget exhausted; 3 spend-cap exhausted or the spend ledger refused a
settlement; 4 committed spend exceeded the authorised cap; 5 owner
authorization refused; 6 workdir already holds the probe store or a trial;
7 probe model call failed (recorded dispatch/executor failure).

``--resume`` and ``run`` take the same exclusive per-workdir lock, so a resume
can never mutate a live run. Under a *different* authorization a resume still
reconciles the attempt accounting (idempotent) but declines spend settlement
with a NOTE and leaves the reservation in flight: settlement is the authorized
action. Pin ``ORCHESTRATOR_AUTHORIZED_AT`` etc. to the recorded values to let
the resume settle.
"""
from __future__ import annotations

import argparse
import contextlib
import dataclasses
import fcntl
import json
import os
import sys
import time
import urllib.error
import urllib.request
from typing import Any, Dict, Iterator, List, Mapping, Optional

REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(REPO_ROOT, "src"))

from orchestrator import (  # noqa: E402
    conformance,
    experiment,
    glossary,
    observability,
    sandbox,
    secrets,
    spend,
)
from orchestrator.model_adapter import (  # noqa: E402
    ModelBudgetRefused,
    ModelClient,
    ModelCompletion,
    ModelOutput,
)
from orchestrator.controller import BudgetExhausted, Controller  # noqa: E402
from orchestrator.executor import ScriptedExecutor  # noqa: E402
from orchestrator.store import EventStore  # noqa: E402

_STEP = {"n": 0}

# In --json mode all narration goes to stderr and one JSON document is written
# to the real stdout, so a CI wrapper can parse it.
_JSON_MODE = False
_REAL_STDOUT = None


def emit_json(payload: Mapping[str, Any]) -> None:
    if _JSON_MODE and _REAL_STDOUT is not None:
        print(json.dumps(payload, sort_keys=True, default=str), file=_REAL_STDOUT, flush=True)

_TRANSCRIPT_FIELD_LIMIT = 8192


def transcript_write(path: str, entry: Mapping[str, Any]) -> None:
    """Append one bounded, redacted transcript line (0600), if enabled."""
    if not path:
        return
    directory = os.path.dirname(path)
    if directory:
        os.makedirs(directory, mode=0o700, exist_ok=True)
        os.chmod(directory, 0o700)
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
    with os.fdopen(descriptor, "a") as handle:
        handle.write(json.dumps(entry, sort_keys=True) + "\n")
    # Enforce the mode even when the transcript already existed.
    os.chmod(path, 0o600)


def log(message: str) -> None:
    _STEP["n"] += 1
    print(f"[{_STEP['n']:02d}] {message}", flush=True)


@contextlib.contextmanager
def workdir_lock(workdir: str) -> Iterator[None]:
    """Exclusive per-workdir interlock for ``run`` and ``--resume``.

    A resume that raced a live run used to fail the live attempt and settle the
    live trial's spend record mid-flight, and the still-running comparison then
    died on an unreserved settlement (Axis 2 review F2). The lock is held for
    the whole operation and released on every exit path; a second holder is
    refused before it touches any trial state."""
    os.makedirs(workdir, mode=0o700, exist_ok=True)
    path = os.path.join(workdir, ".smoke-run.lock")
    with open(path, "a+") as handle:
        os.chmod(path, 0o600)
        try:
            fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            raise SystemExit(
                f"workdir {workdir} is locked by another smoke_run process"
                " (a run or --resume holds the exclusive workdir lock): wait for"
                " it to finish, or use a different ORCHESTRATOR_WORKDIR"
            )
        try:
            yield
        finally:
            fcntl.flock(handle.fileno(), fcntl.LOCK_UN)


def flag(name: str, default: bool = False) -> bool:
    value = os.environ.get(name)
    if value is None:
        return default
    return value.strip().lower() in ("1", "true", "yes", "on")


def number(name: str, default: float) -> float:
    raw = os.environ.get(name)
    return float(raw) if raw not in (None, "") else float(default)


def integer(name: str, default: int) -> int:
    raw = os.environ.get(name)
    return int(raw) if raw not in (None, "") else int(default)


# ---------------------------------------------------------------------------
# Real provider client (OpenAI-compatible chat completions)
# ---------------------------------------------------------------------------

# Built from the authoritative catalogue so the instruction can never drift
# from what the reducer will accept (docs/glossary.md#semantic-verdicts).
_SEMANTIC_VERDICTS = tuple(glossary.semantic_verdicts())
_SYSTEM_INSTRUCTION = (
    "You are a reviewer inside a deterministic harness. Reply with a single JSON "
    "object and nothing else, with exactly these fields: "
    '{"subject_reference": "<short id>", '
    '"verdict": "<one of: ' + "|".join(_SEMANTIC_VERDICTS) + '>", '
    '"rationale": "<one non-empty sentence>"}.'
)


def _extract_json_object(text: str) -> Dict[str, Any]:
    """Tolerate the common provider habits around strict JSON: code fences and
    surrounding prose. The extracted object is still validated strictly."""
    cleaned = text.strip()
    if cleaned.startswith("```"):
        lines = cleaned.splitlines()
        if lines and lines[0].startswith("```"):
            lines = lines[1:]
        if lines and lines[-1].strip().startswith("```"):
            lines = lines[:-1]
        cleaned = "\n".join(lines).strip()
    start = cleaned.find("{")
    end = cleaned.rfind("}")
    if start == -1 or end < start:
        raise ValueError("no JSON object in the completion")
    parsed = json.loads(cleaned[start : end + 1])
    if not isinstance(parsed, dict):
        raise ValueError("the completion JSON is not an object")
    return parsed


def parse_provider_completion(content: str) -> Dict[str, str]:
    """Normalise and validate a provider completion into a SEMANTIC_EVALUATION
    body. A non-catalogued verdict, an empty subject, or an empty rationale is
    refused (fail closed; no output is admitted)."""
    parsed = _extract_json_object(content)
    subject = str(parsed.get("subject_reference", "")).strip()
    verdict = str(parsed.get("verdict", "")).strip().upper()
    rationale = str(parsed.get("rationale", "")).strip()
    if not subject:
        raise ValueError("subject_reference is empty")
    if not rationale:
        raise ValueError("rationale is empty")
    if verdict not in _SEMANTIC_VERDICTS:
        raise ValueError(
            f"verdict {verdict[:64]!r} is not catalogued; expected one of "
            f"{_SEMANTIC_VERDICTS}"
        )
    return {"subject_reference": subject, "verdict": verdict, "rationale": rationale}


class OpenAICompatibleClient(ModelClient):
    """A real network client with frozen pricing and declared token ceilings.

    It refuses an expired credential, declares ``(max_input_tokens,
    max_output_tokens)`` so the controller can bound the call before dispatch,
    and prices the reported usage from frozen per-million-token rates. No secret
    is ever logged, and no usage number is clipped.

    Provider faults (Axis 2 decision): a 429 is a rejection before processing
    (a conforming provider does not bill it), so it gets a bounded backoff
    retry *within* the one per-call deadline. A 5xx or a timeout is an
    ambiguous outcome that may already be billed: it fails closed with no
    hidden retry, so every billable dispatch stays one recorded attempt that
    settles exactly once and any retry is a fresh attempt through the repair
    policy.
    """

    def __init__(
        self,
        profile: experiment.ModelProfile,
        *,
        base_url: str,
        path: str,
        credential: secrets.Credential,
        units: str,
        price_input_per_mtok: float,
        price_output_per_mtok: float,
        max_input_tokens: int,
        timeout: float,
        transcript_path: str = "",
        credentials: tuple = (),
        max_reply_bytes: int = 1_048_576,
        sampling_seed: Optional[int] = None,
        max_rate_limit_retries: int = 2,
        rate_limit_backoff: float = 0.5,
    ):
        self.profile = profile
        self.base_url = base_url.rstrip("/")
        self.path = path if path.startswith("/") else "/" + path
        self.credential = credential
        self.units = units
        self.price_input_per_mtok = price_input_per_mtok
        self.price_output_per_mtok = price_output_per_mtok
        self.max_input_tokens = int(max_input_tokens)
        self.timeout = float(timeout)
        self.transcript_path = transcript_path
        self.credentials = tuple(credentials)
        self.max_reply_bytes = int(max_reply_bytes)
        # The provider sampling seed derived from the frozen trial seed; this is
        # what makes a multi-seed run vary the model's sampling, not only the
        # trial identity (step 2).
        self.sampling_seed = sampling_seed
        self.max_rate_limit_retries = max(0, int(max_rate_limit_retries))
        self.rate_limit_backoff = max(0.0, float(rate_limit_backoff))

    def _record(self, request, prompt, content, error=None) -> None:
        if not self.transcript_path:
            return
        entry = {
            "ts": time.time(),
            # The adapter passes call_id/call_key; fall back to the
            # attempt/node names for direct in-process use.
            "attempt_id": request.get("call_id") or request.get("attempt_id"),
            "node_id": request.get("call_key") or request.get("node_id"),
            "prompt_hash": request.get("prompt_hash"),
            "prompt": secrets.redact_text(prompt or "", self.credentials)[
                :_TRANSCRIPT_FIELD_LIMIT
            ],
            "response": secrets.redact_text(content or "", self.credentials)[
                :_TRANSCRIPT_FIELD_LIMIT
            ],
        }
        if error is not None:
            entry["error"] = str(error)[:512]
        transcript_write(self.transcript_path, entry)

    def _require_live_credential(self) -> None:
        if time.time() >= self.credential.expires_at:
            raise ModelBudgetRefused(
                f"credential {self.credential.credential_id!r} expired"
            )

    def _post(self, body: Mapping[str, Any], deadline: float) -> Dict[str, Any]:
        """POST with a bounded reply and an enforced total deadline.

        The reply is read in blocks and stops at ``max_reply_bytes``; the socket
        timeout and a between-read deadline check bound the whole call by
        ``deadline`` (reply-boundary review F1, F2)."""
        remaining = max(0.1, min(self.timeout, deadline - time.monotonic()))
        http_request = urllib.request.Request(
            f"{self.base_url}{self.path}",
            data=json.dumps(body).encode(),
            headers={
                "Content-Type": "application/json",
                # The secret is used only here and is never logged.
                "Authorization": f"Bearer {self.credential.secret}",
            },
            method="POST",
        )
        with urllib.request.urlopen(http_request, timeout=remaining) as response:
            blocks = []
            total = 0
            # ``read1`` returns as soon as some data is available (at most one
            # system call) instead of blocking to fill the buffer, so the
            # deadline check between reads is actually reached for a dripping
            # reply (reply-boundary review F2).
            read = getattr(response, "read1", None) or response.read
            while True:
                if time.monotonic() > deadline:
                    raise TimeoutError("provider reply exceeded the wall deadline")
                block = read(65536)
                if not block:
                    break
                total += len(block)
                if total > self.max_reply_bytes:
                    raise RuntimeError(
                        "provider reply exceeds ORCHESTRATOR_MAX_REPLY_BYTES "
                        f"({self.max_reply_bytes})"
                    )
                blocks.append(block)
            raw = b"".join(blocks)
            try:
                return json.loads(raw.decode())
            except (ValueError, UnicodeDecodeError) as error:
                # A reply that is not JSON is a provider-protocol failure: raise
                # the same recorded RuntimeError as the other bound failures.
                raise RuntimeError(f"provider reply is not valid JSON: {error}") from error

    def _rate_limit_pause(self, error: urllib.error.HTTPError, attempt: int,
                          remaining: float) -> float:
        """The bounded sleep before one 429 retry.

        Honours a ``Retry-After`` delta-seconds header, falls back to the
        doubling base backoff, and never sleeps past the call deadline: the
        retry budget lives inside the one per-call deadline, not on top of it.
        """
        pause = self.rate_limit_backoff * (2 ** (attempt - 1))
        retry_after = (error.headers or {}).get("Retry-After") if error.headers else None
        if retry_after is not None:
            try:
                pause = max(0.0, float(retry_after))
            except ValueError:
                pass
        return min(pause, max(0.0, remaining - 0.05))

    def max_tokens(self, request: Mapping[str, Any]) -> tuple:
        return (self.max_input_tokens, int(self.profile.max_output_tokens))

    def max_cost(self, request: Mapping[str, Any]) -> float:
        # Worst-case declared bound: the full input ceiling plus the output cap.
        return (
            self.max_input_tokens / 1_000_000.0 * self.price_input_per_mtok
            + int(self.profile.max_output_tokens) / 1_000_000.0
            * self.price_output_per_mtok
        )

    def complete(self, request: Mapping[str, Any]) -> ModelCompletion:
        self._require_live_credential()
        started = time.time()
        body = {
            "model": self.profile.model_id,
            "messages": [
                {"role": "system", "content": _SYSTEM_INSTRUCTION},
                {"role": "user", "content": request.get("prompt") or ""},
            ],
            "temperature": self.profile.temperature,
            "max_tokens": int(self.profile.max_output_tokens),
            **({"seed": int(self.sampling_seed)} if self.sampling_seed is not None else {}),
            # Ask for a JSON object. If the provider rejects the field, the
            # request is retried once without it (a 400 is not a billed call).
            "response_format": {"type": "json_object"},
        }
        request_timeout = request.get("timeout_seconds")
        budget = (
            min(self.timeout, float(request_timeout))
            if request_timeout not in (None, "")
            else self.timeout
        )
        deadline = time.monotonic() + max(0.1, float(budget))
        # Dispatch loop: the only implicit re-sends are (a) one retry without
        # ``response_format`` after a 400 (a request-configuration rejection,
        # not a billed call) and (b) bounded backoff retries after a 429 (a
        # rate-limit rejection before processing). A 5xx or a timeout is an
        # ambiguous, possibly billed outcome: it fails closed and is re-issued
        # only as a fresh attempt through the repair policy (Axis 2 decision).
        allow_format_retry = "response_format" in body
        rate_retries = 0
        while True:
            try:
                payload = self._post(body, deadline)
                break
            except urllib.error.HTTPError as error:
                if error.code == 400 and allow_format_retry:
                    allow_format_retry = False
                    body.pop("response_format", None)
                    self._record(
                        request, request.get("prompt"), None,
                        "HTTP 400; retrying once without response_format",
                    )
                    continue
                if error.code == 429 and rate_retries < self.max_rate_limit_retries:
                    remaining = deadline - time.monotonic()
                    if remaining > 0.05:
                        rate_retries += 1
                        pause = self._rate_limit_pause(error, rate_retries, remaining)
                        self._record(
                            request, request.get("prompt"), None,
                            f"HTTP 429; bounded retry {rate_retries}/"
                            f"{self.max_rate_limit_retries} after {pause:.2f}s",
                        )
                        time.sleep(pause)
                        continue
                self._record(request, request.get("prompt"), None, error)
                raise RuntimeError(f"provider HTTP {error.code}") from error
            except TimeoutError as error:
                self._record(request, request.get("prompt"), None, error)
                raise RuntimeError(f"provider reply exceeded the wall deadline: {error}") from error
            except urllib.error.URLError as error:
                self._record(request, request.get("prompt"), None, error)
                raise RuntimeError(f"provider transport error: {error.reason}") from error
            except RuntimeError as error:
                # Bound failures raised while reading the reply (for example the
                # hard reply-size cap): record them before surfacing so the
                # transcript shows every failure, not only transport errors.
                self._record(request, request.get("prompt"), None, error)
                raise
        choice = (payload.get("choices") or [{}])[0] or {}
        if choice.get("finish_reason") == "length":
            self._record(
                request, request.get("prompt"), "", "completion truncated at max_tokens"
            )
            raise RuntimeError(
                "provider completion was truncated at max_tokens; raise "
                "ORCHESTRATOR_MAX_OUTPUT_TOKENS"
            )
        usage = payload.get("usage") or {}
        input_tokens = int(usage.get("prompt_tokens") or 0)
        output_tokens = int(usage.get("completion_tokens") or 0)
        message = choice.get("message", {}) or {}
        content = message.get("content")
        if isinstance(content, list):
            # Some providers return content as typed parts.
            content = "".join(
                part.get("text", "")
                for part in content
                if isinstance(part, Mapping)
            )
        content = content or ""
        try:
            output = parse_provider_completion(content)
        except (ValueError, TypeError, RecursionError) as error:
            # Fail closed: a non-conforming completion admits no output. The
            # bounded snippet makes a provider-output mismatch diagnosable, and
            # the opt-in transcript keeps the full bounded reply for debugging.
            # Mapping (reply-boundary review F4): a refusal at the parse layer
            # produces no typed output, so it is recorded as a provider/protocol
            # failure (DISPATCH_FAILED) with the attempt failed and settled.
            # MODEL_OUTPUT_REJECTED applies when a *typed* output fails
            # admission, on the adapter path.
            snippet = " ".join(content.split())[:200]
            self._record(request, request.get("prompt"), content, error)
            raise RuntimeError(
                f"provider completion was not the required JSON: {error}; "
                f"content[:200]={snippet!r}"
            ) from error
        self._record(request, request.get("prompt"), content)
        cost = (
            input_tokens / 1_000_000.0 * self.price_input_per_mtok
            + output_tokens / 1_000_000.0 * self.price_output_per_mtok
        )
        return ModelCompletion(
            outputs=(ModelOutput("SEMANTIC_EVALUATION", output),),
            cost=cost,
            units=self.units,
            model_id=self.profile.model_id,
            model_version=self.profile.model_version,
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            started_at=started,
            finished_at=time.time(),
        )


# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------


@dataclasses.dataclass
class Settings:
    mode: str
    workdir: str
    owner: str
    cap: float
    authorized_at: str
    method: str
    approval_ref: str
    seeds: Tuple[int, ...]
    model_cost: float
    per_attempt_commitment: float
    max_model_calls: int
    max_actions: int
    max_nodes: int
    max_depth: int
    max_input_tokens: int
    max_output_tokens: int
    run_max_input_tokens: int
    run_max_output_tokens: int
    wall_seconds: int
    require_conformance: bool
    confirm_real: bool
    provider_base_url: str
    provider_path: str
    provider_model: str
    provider_model_version: str
    provider_api_key: str
    price_input: float
    price_output: float
    units: str
    provider_timeout: float
    credential_ttl: float
    revoke_url: str
    debug_transcript: str
    max_reply_bytes: int
    max_rate_limit_retries: int
    rate_limit_backoff: float


def parse_seeds() -> Tuple[int, ...]:
    """The frozen trial seeds: ``ORCHESTRATOR_SEEDS=1001,1002`` or a single
    ``ORCHESTRATOR_SEED``. A multi-seed selection is the full experiment matrix
    (every arm x every seed)."""
    raw = os.environ.get("ORCHESTRATOR_SEEDS", "").strip()
    if raw:
        seeds = tuple(int(part) for part in raw.split(",") if part.strip())
    else:
        seeds = (integer("ORCHESTRATOR_SEED", 1001),)
    if not seeds or any(seed <= 0 for seed in seeds):
        raise SystemExit("ORCHESTRATOR_SEEDS must be a non-empty list of positive integers")
    return seeds


def load_settings() -> Settings:
    return Settings(
        mode=os.environ.get("ORCHESTRATOR_MODE", "scripted").strip().lower(),
        workdir=os.path.abspath(
            os.environ.get("ORCHESTRATOR_WORKDIR", os.path.join(os.getcwd(), "smoke-run"))
        ),
        owner=os.environ.get("ORCHESTRATOR_OWNER", "").strip(),
        cap=number("ORCHESTRATOR_CAP", 0.0),
        authorized_at=os.environ.get("ORCHESTRATOR_AUTHORIZED_AT", "").strip()
        or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        method=os.environ.get("ORCHESTRATOR_AUTH_METHOD", "owner-decision").strip(),
        approval_ref=os.environ.get("ORCHESTRATOR_APPROVAL_REF", "").strip(),
        seeds=parse_seeds(),
        model_cost=number("ORCHESTRATOR_MODEL_COST", 100.0),
        per_attempt_commitment=number("ORCHESTRATOR_PER_ATTEMPT_COMMITMENT", 5.0),
        max_model_calls=integer("ORCHESTRATOR_MAX_MODEL_CALLS", 4),
        max_actions=integer("ORCHESTRATOR_MAX_ACTIONS", 8),
        max_nodes=integer("ORCHESTRATOR_MAX_NODES", 8),
        max_depth=integer("ORCHESTRATOR_MAX_DEPTH", 3),
        max_input_tokens=integer("ORCHESTRATOR_MAX_INPUT_TOKENS", 4000),
        max_output_tokens=integer("ORCHESTRATOR_MAX_OUTPUT_TOKENS", 1024),
        run_max_input_tokens=integer("ORCHESTRATOR_RUN_MAX_INPUT_TOKENS", 32768),
        run_max_output_tokens=integer("ORCHESTRATOR_RUN_MAX_OUTPUT_TOKENS", 8192),
        wall_seconds=integer("ORCHESTRATOR_WALL_SECONDS", 120),
        require_conformance=flag("ORCHESTRATOR_REQUIRE_CONFORMANCE", True),
        confirm_real=os.environ.get("ORCHESTRATOR_CONFIRM_REAL", "").strip().lower()
        == "yes",
        provider_base_url=os.environ.get("ORCHESTRATOR_PROVIDER_BASE_URL", "").strip(),
        provider_path=os.environ.get("ORCHESTRATOR_PROVIDER_PATH", "/v1/chat/completions"),
        provider_model=os.environ.get("ORCHESTRATOR_PROVIDER_MODEL", "").strip(),
        provider_model_version=os.environ.get(
            "ORCHESTRATOR_PROVIDER_MODEL_VERSION", "1"
        ).strip(),
        provider_api_key=os.environ.get("ORCHESTRATOR_PROVIDER_API_KEY", ""),
        price_input=number("ORCHESTRATOR_PRICE_INPUT_PER_MTOK", 0.0),
        price_output=number("ORCHESTRATOR_PRICE_OUTPUT_PER_MTOK", 0.0),
        units=os.environ.get("ORCHESTRATOR_PROVIDER_UNITS", "USD").strip(),
        provider_timeout=number("ORCHESTRATOR_PROVIDER_TIMEOUT", 60.0),
        credential_ttl=number("ORCHESTRATOR_CREDENTIAL_TTL_SECONDS", 3600.0),
        revoke_url=os.environ.get("ORCHESTRATOR_REVOKE_URL", "").strip(),
        debug_transcript=os.environ.get("ORCHESTRATOR_DEBUG_TRANSCRIPT", "").strip(),
        max_reply_bytes=integer("ORCHESTRATOR_MAX_REPLY_BYTES", 1_048_576),
        max_rate_limit_retries=integer("ORCHESTRATOR_MAX_RATE_LIMIT_RETRIES", 2),
        rate_limit_backoff=number("ORCHESTRATOR_RATE_LIMIT_BACKOFF", 0.5),
    )


def validate(settings: Settings) -> None:
    if settings.mode not in ("scripted", "real"):
        raise SystemExit("ORCHESTRATOR_MODE must be 'scripted' or 'real'")
    if not settings.owner:
        raise SystemExit(
            "ORCHESTRATOR_OWNER is required: the owner who authorises the cap"
        )
    if settings.cap <= 0:
        raise SystemExit(
            "ORCHESTRATOR_CAP is required and must be > 0 (COST_UNITS)"
        )
    if settings.mode == "real":
        missing = [
            name
            for name, value in (
                ("ORCHESTRATOR_PROVIDER_BASE_URL", settings.provider_base_url),
                ("ORCHESTRATOR_PROVIDER_MODEL", settings.provider_model),
                ("ORCHESTRATOR_PROVIDER_API_KEY", settings.provider_api_key),
            )
            if not value
        ]
        if missing:
            raise SystemExit("real mode requires: " + ", ".join(missing))
        if not settings.confirm_real:
            raise SystemExit(
                "real mode spends money: set ORCHESTRATOR_CONFIRM_REAL=yes to proceed"
            )
        if settings.units not in ("USD", "COST_UNITS"):
            raise SystemExit(
                f"ORCHESTRATOR_PROVIDER_UNITS {settings.units!r} is not catalogued "
                "(USD, COST_UNITS)"
            )
        if settings.price_input <= 0 and settings.price_output <= 0:
            raise SystemExit(
                "real mode requires a frozen price: set ORCHESTRATOR_PRICE_INPUT_PER_MTOK "
                "and/or ORCHESTRATOR_PRICE_OUTPUT_PER_MTOK"
            )
        worst_case = (
            settings.max_input_tokens / 1_000_000.0 * settings.price_input
            + settings.max_output_tokens / 1_000_000.0 * settings.price_output
        )
        if worst_case > settings.per_attempt_commitment:
            raise SystemExit(
                f"declared worst-case call cost {worst_case:.6f} exceeds "
                f"ORCHESTRATOR_PER_ATTEMPT_COMMITMENT {settings.per_attempt_commitment}: "
                "lower ORCHESTRATOR_MAX_INPUT_TOKENS / _OUTPUT_TOKENS or the prices, "
                "or raise the commitment (and the cap)"
            )


# ---------------------------------------------------------------------------
# Cap worksheet
# ---------------------------------------------------------------------------


def experiment_limits(settings: Settings) -> experiment.ExperimentLimits:
    """The frozen run limits.

    The per-call declared caps (``ORCHESTRATOR_MAX_*_TOKENS``) bound what a
    client may send; the run aggregate ceilings
    (``ORCHESTRATOR_RUN_MAX_*_TOKENS``) bound a whole trial. Conflating them
    makes the first call consume the run token budget and starves the rest
    (observed in the first real run)."""
    return dataclasses.replace(
        experiment.placeholder_limits(),
        model_cost=settings.model_cost,
        per_attempt_commitment=settings.per_attempt_commitment,
        model_calls=settings.max_model_calls,
        root_model_input_tokens=settings.run_max_input_tokens,
        root_model_output_tokens=settings.run_max_output_tokens,
        wall_clock_seconds=settings.wall_seconds,
        actions=settings.max_actions,
        nodes=settings.max_nodes,
        maximum_depth=settings.max_depth,
    )


def cap_worksheet(settings: Settings) -> Mapping[str, float]:
    # The frozen manifest covers every arm; the matrix is arms x seeds.
    trials = len(experiment.ARM_ORDER) * len(settings.seeds)
    per_trial = settings.model_cost + settings.per_attempt_commitment
    required = trials * per_trial
    return {
        "trials": float(trials),
        "model_cost_per_trial": settings.model_cost,
        "f6_headroom_per_trial": settings.per_attempt_commitment,
        "required_cap": required,
        "authorized_cap": settings.cap,
        "margin": settings.cap - required,
    }


def print_worksheet(worksheet: Mapping[str, float]) -> None:
    log("cap worksheet (COST_UNITS):")
    for key in (
        "trials",
        "model_cost_per_trial",
        "f6_headroom_per_trial",
        "required_cap",
        "authorized_cap",
        "margin",
    ):
        print(f"      {key:28s} {worksheet[key]:.4f}")
    if worksheet["margin"] < 0:
        raise SystemExit(
            "the authorised cap is below the required minimum; raise ORCHESTRATOR_CAP "
            "or lower the per-trial bounds"
        )


# ---------------------------------------------------------------------------
# Inspect / resume
# ---------------------------------------------------------------------------


def inspect(settings: Settings) -> None:
    log(f"inspecting workdir {settings.workdir}")
    ledger_path = os.path.join(settings.workdir, spend.ExperimentSpendLedger.FILE_NAME)
    ledger = None
    if os.path.exists(ledger_path):
        with open(ledger_path) as handle:
            ledger = json.load(handle)
        if not _JSON_MODE:
            print("      spend ledger:", json.dumps(ledger, indent=2, sort_keys=True))
    elif not _JSON_MODE:
        print("      no experiment spend ledger (probe runs do not create one)")
    probe = None
    probe_db = os.path.join(settings.workdir, "probe", "events.db")
    if os.path.exists(probe_db):
        store = EventStore(probe_db)
        try:
            state = store.state("PROBE-1")
            probe = {
                "outcome": state.outcome,
                "charged": state.ledger.total_charged,
                "overrun": state.ledger.total_overrun,
                "attempts": len(state.attempts),
                "calls": [],
            }
            for event in store.history("PROBE-1"):
                if event.event_type == "EXECUTOR_OBSERVATION_ADMITTED":
                    report = (
                        (event.payload.get("observation") or {}).get("cost_report") or {}
                    )
                    probe["calls"].append(
                        {
                            "attempt_id": event.payload.get("attempt_id"),
                            "committed": report.get("committed"),
                            "actual": report.get("actual"),
                            "units": report.get("units"),
                            "model_usage": report.get("model_usage"),
                            "budget_exhausted": report.get("budget_exhausted"),
                        }
                    )
            if not _JSON_MODE:
                print(
                    f"      probe run PROBE-1: outcome={probe['outcome']} "
                    f"charged={probe['charged']} overrun={probe['overrun']} "
                    f"attempts={probe['attempts']}"
                )
                for call in probe["calls"]:
                    print(f"      probe call {json.dumps(call, sort_keys=True, default=str)}")
        finally:
            store.close()
    trials = []
    for arm in experiment.ARM_ORDER:
        for seed in settings.seeds:
            try:
                record = experiment.inspect_trial(settings.workdir, arm, seed)
            except experiment.ExperimentError:
                continue
            trials.append(record)
            if not _JSON_MODE:
                print(f"      trial {arm}/{seed}: {json.dumps(record, sort_keys=True, default=str)}")
    emit_json(
        {
            "workdir": settings.workdir,
            "ledger": ledger,
            "probe": probe,
            "trials": trials,
        }
    )


def resume(settings: Settings) -> None:
    log("recovery: reopening each trial's store and reconciling unfinished work")
    trials_root = os.path.join(settings.workdir, "trials")
    if not os.path.isdir(trials_root):
        raise SystemExit("no trials directory to resume")
    with workdir_lock(settings.workdir):
        _resume_locked(settings, trials_root)


def _resume_locked(settings: Settings, trials_root: str) -> None:
    # R05 audited re-issue: in real mode the recovery boundary gets a fresh
    # short-lived credential from the operator's env/secret source (the old one
    # died with the crashed process). Scripted runs carry no credentials.
    recovery_source = secrets.SecretsSource()
    recovery_credentials = None
    if settings.mode == "real" and settings.provider_api_key:
        recovery_credentials = recovery_source.issue(
            "MODEL_ENDPOINT",
            credential_id=f"model-endpoint-recovered-{int(time.time())}",
            ttl_seconds=settings.credential_ttl,
            subject=settings.provider_base_url,
            secret=settings.provider_api_key,
        )
    authorization = spend.ExperimentAuthorization(
        owner=settings.owner,
        limit=settings.cap,
        authorized_at=settings.authorized_at,
        method=settings.method,
    )
    ledger = None
    try:
        ledger = spend.open_spend_ledger(settings.workdir, authorization)
    except spend.SpendLedgerError:
        # The attempt accounting is still reconciled; the spend reservation
        # stays visibly in flight until the resume is bound to the recorded
        # authorisation (same owner/limit/authorized_at/method as the run).
        print(
            "      NOTE: spend ledger is bound to a different authorisation;"
            " trial reservations stay in flight until --resume is run with the"
            " recorded authorisation env"
        )
    for name in sorted(os.listdir(trials_root)):
        db_path = os.path.join(trials_root, name, "events.db")
        if not os.path.exists(db_path):
            continue
        store = EventStore(db_path)
        try:
            controller = Controller(
                store,
                ScriptedExecutor({}),
                secrets_source=recovery_source,
            )
            run_id = f"EXP-{name.rsplit('-', 1)[0]}-{name.rsplit('-', 1)[1]}"
            if recovery_credentials is not None:
                # R05: the pre-crash credential cannot be restored, so recovery
                # re-issues through the audited CREDENTIAL_ISSUED lifecycle
                # (retire the stale record, issue a fresh one) before any
                # resumed boundary admission.
                controller.reissue_credentials(run_id, [recovery_credentials])
            recovered = controller.recover(run_id)
            print(f"      {run_id}: recovered {len(recovered)} attempt(s)")
            if ledger is not None and run_id in ledger.status().get("in_flight", {}):
                # Recovery has reconciled every attempt, so the trial's
                # conservative in-flight charge is now an authoritative actual:
                # settle it and release the reservation instead of leaving the
                # liability outstanding forever (R14).
                total = float(controller.store.state(run_id).ledger.total_charged)
                ledger.settle(run_id, total, status="RECOVERED")
                print(f"      {run_id}: spend settled at {total} (RECOVERED)")
        except Exception as error:  # noqa: BLE001 - reported, not fatal
            print(f"      {name}: recovery failed: {type(error).__name__}: {error}")
        finally:
            store.close()


# ---------------------------------------------------------------------------
# Main pipeline
# ---------------------------------------------------------------------------


def revoke_credential(settings: Settings) -> None:
    """Best-effort provider revocation when ORCHESTRATOR_REVOKE_URL is set.

    The credential is always dropped from memory at process exit and always
    expires at its TTL; the URL is the explicit provider-side revocation."""
    if not settings.revoke_url:
        return
    log("revoking the provider credential")
    try:
        request = urllib.request.Request(settings.revoke_url, method="POST", data=b"{}")
        urllib.request.urlopen(request, timeout=settings.provider_timeout)
        print("      revocation request accepted")
    except Exception as error:  # noqa: BLE001 - reported, not fatal
        print(f"      revocation failed (revoke manually): {error}")


def resolve_transcript_path(settings: Settings) -> str:
    """The opt-in debug transcript path (0600): "1" means the workdir default."""
    value = settings.debug_transcript
    if not value:
        return ""
    if value in ("1", "true", "yes", "on"):
        return os.path.join(settings.workdir, "debug", "transcript.jsonl")
    return os.path.abspath(value)


def build_real_client_factory(settings: Settings, source: secrets.SecretsSource):
    credential = source.issue(
        "MODEL_ENDPOINT",
        credential_id="model-endpoint-smoke-" + "-".join(str(s) for s in settings.seeds),
        ttl_seconds=settings.credential_ttl,
        subject=settings.provider_base_url,
        secret=settings.provider_api_key,
    )
    log(
        f"issued MODEL_ENDPOINT credential {credential.credential_id!r} "
        f"(digest {credential.redacted_digest}, ttl {settings.credential_ttl:.0f}s)"
    )

    transcript_path = resolve_transcript_path(settings)

    def factory(profile: experiment.ModelProfile, seed: Optional[int]) -> ModelClient:
        return OpenAICompatibleClient(
            profile,
            base_url=settings.provider_base_url,
            path=settings.provider_path,
            credential=credential,
            units=settings.units,
            price_input_per_mtok=settings.price_input,
            price_output_per_mtok=settings.price_output,
            max_input_tokens=settings.max_input_tokens,
            timeout=settings.provider_timeout,
            transcript_path=transcript_path,
            credentials=source.credentials(),
            max_reply_bytes=settings.max_reply_bytes,
            sampling_seed=seed,
            max_rate_limit_retries=settings.max_rate_limit_retries,
            rate_limit_backoff=settings.rate_limit_backoff,
        )

    return factory, credential


def run(settings: Settings) -> int:
    os.makedirs(settings.workdir, mode=0o700, exist_ok=True)
    with workdir_lock(settings.workdir):
        return _run_locked(settings)


def _run_locked(settings: Settings) -> int:
    log(f"revision: {os.popen('git -C %s rev-parse HEAD' % REPO_ROOT).read().strip()}")
    log(
        f"mode={settings.mode} seeds={list(settings.seeds)} "
        f"arms={len(experiment.ARM_ORDER)} workdir={settings.workdir}"
    )
    print_worksheet(cap_worksheet(settings))

    log("preflight: conformance suite")
    if settings.require_conformance:
        report = conformance.run_full_suite()
        print(f"      conformance passed={report.passed} failures={report.failures()}")
        if not report.passed:
            raise SystemExit("conformance gate is red; refusing to run")
    else:
        print("      skipped (ORCHESTRATOR_REQUIRE_CONFORMANCE=0)")

    log("preflight: sandbox capability")
    capabilities = sandbox.capabilities()
    print(
        f"      {sandbox.PROFILE_NAMESPACE_V1} available={capabilities.profile_available}"
    )
    if not capabilities.profile_available:
        raise SystemExit(f"cannot provision the sandbox: {capabilities.unavailable_reason()}")

    log("owner authorisation: opening the durable spend ledger")
    authorization = spend.ExperimentAuthorization(
        owner=settings.owner,
        limit=settings.cap,
        authorized_at=settings.authorized_at,
        method=settings.method,
    )
    ledger_path = os.path.join(settings.workdir, spend.ExperimentSpendLedger.FILE_NAME)
    if os.path.exists(ledger_path):
        print(
            f"      NOTE: {settings.workdir} already holds a spend ledger. An"
            " experiment directory is bound to one authorisation and its trials"
            " cannot be overwritten; a rerun needs a fresh workdir (or pin"
            " ORCHESTRATOR_AUTHORIZED_AT to the recorded value and use --resume)."
        )
    try:
        ledger = spend.open_spend_ledger(settings.workdir, authorization)
    except spend.SpendLedgerError as error:
        log(f"REFUSED: the workdir is bound to a different authorisation: {error}")
        print(
            "      Remediation: choose a fresh ORCHESTRATOR_WORKDIR (recommended), or"
            " rebuild the ledger with exactly the recorded owner/limit/authorized_at/method."
        )
        emit_json({"workdir": settings.workdir, "code": 5, "error": str(error)})
        return 5
    print(
        f"      authorized by {settings.owner!r} limit={authorization.limit} "
        f"at {authorization.authorized_at} ({settings.method})"
    )
    if settings.approval_ref:
        print(f"      approval reference: {settings.approval_ref}")

    source = secrets.SecretsSource()
    credential: Optional[secrets.Credential] = None
    if settings.mode == "real":
        factory, credential = build_real_client_factory(settings, source)
        experiment.set_model_client_factory(factory)
        log(
            "real provider client installed with declared token ceilings "
            f"({settings.max_input_tokens} in / {settings.max_output_tokens} out) "
            "and frozen prices"
        )
    else:
        experiment.set_model_client_factory(None)
        log("scripted client installed (no network, synthetic cost)")
    experiment.set_secrets_source(source)

    log("building the frozen target and hidden oracle")
    target = experiment.build_fixed_target(settings.workdir)
    oracle_manifest = experiment.build_hidden_oracle(target)

    log("calibrating the oracle (local sandbox checks, no model spend)")
    calibration = experiment.calibrate_oracle(target, oracle_manifest, settings.workdir)

    log("freezing a one-trial manifest")
    limits = experiment_limits(settings)
    arm_assignment = tuple((arm, settings.seeds) for arm in experiment.ARM_ORDER)
    if settings.mode == "real":
        real_profile = experiment.ModelProfile(
            model_id=settings.provider_model,
            model_version=settings.provider_model_version,
            temperature=0.0,
            top_p=1.0,
            max_output_tokens=settings.max_output_tokens,
            input_tokens_per_call=settings.max_input_tokens,
            output_tokens_per_call=settings.max_output_tokens,
            cost_per_call=settings.per_attempt_commitment,
        )
        experiment.set_model_profile(real_profile)
        log(f"frozen model identity {real_profile.model_id}:{real_profile.model_version}")
    manifest = experiment.freeze_manifest(
        target=target,
        oracle_manifest=oracle_manifest,
        limits=limits,
        calibration=calibration,
        model_profile=experiment.MODEL_PROFILE,
        trial_seeds=settings.seeds,
        arm_assignment=arm_assignment,
        pilot_calibration_method="smoke-runner (no pilots)",
    )
    print(f"      manifest {manifest.manifest_id} hash={manifest.content_hash()}")

    log("running the measured comparison (one trial per arm) under the cap")
    try:
        comparison = experiment.run_measured_comparison(
            manifest, oracle_manifest, settings.workdir, spend_ledger=ledger
        )
    except BudgetExhausted as error:
        log(f"STOP: budget/limit exhausted: {error}")
        print(json.dumps(ledger.status(), indent=2, sort_keys=True))
        emit_json({"workdir": settings.workdir, "code": 2, "error": str(error), "ledger": ledger.status()})
        return 2
    except spend.SpendCapExceeded as error:
        log(f"STOP: experiment cap exhausted: {error}")
        print(json.dumps(ledger.status(), indent=2, sort_keys=True))
        emit_json({"workdir": settings.workdir, "code": 3, "error": str(error), "ledger": ledger.status()})
        return 3
    except spend.SpendLedgerError as error:
        # Defence in depth: a ledger integrity refusal (for example a settlement
        # that no longer has a reservation) must not escape the runner as a
        # traceback (Axis 2 review F2).
        log(f"REFUSED: the spend ledger refused the operation: {error}")
        print(
            "      Remediation: inspect experiment-spend.json and the trial"
            " stores; --resume reconciles an interrupted workdir under its"
            " recorded authorization."
        )
        print(json.dumps(ledger.status(), indent=2, sort_keys=True))
        emit_json({"workdir": settings.workdir, "code": 3, "error": str(error), "ledger": ledger.status()})
        return 3
    except experiment.ExperimentError as error:
        log(f"REFUSED: {error}")
        print(
            "      Remediation: existing trials are never overwritten. Use a fresh"
            " ORCHESTRATOR_WORKDIR, or --inspect / --resume to read recorded state."
        )
        print(json.dumps(ledger.status(), indent=2, sort_keys=True))
        emit_json({"workdir": settings.workdir, "code": 6, "error": str(error), "ledger": ledger.status()})
        return 6

    log("results")
    for trial in comparison.trials:
        print(
            f"      {trial.arm}/{trial.seed}: classification={trial.classification} "
            f"controller_outcome={trial.controller_outcome} "
            f"cost={trial.total_cost} budget_exhaustion={trial.budget_exhaustion}"
        )
        try:
            record = experiment.inspect_trial(settings.workdir, trial.arm, trial.seed)
            backend = observability.ObservabilityBackend(
                EventStore(os.path.join(record["trial_root"], "events.db"))
            )
            print(
                f"      reconstructed classification="
                f"{backend.reconstruct_classification(trial.run_id)}"
            )
        except Exception as error:  # noqa: BLE001 - diagnostic only
            print(f"      reconstruction unavailable: {type(error).__name__}: {error}")

    log("spend ledger status")
    status = ledger.status()
    print(json.dumps(status, indent=2, sort_keys=True))
    if status["committed"] > authorization.limit:
        log("STOP: committed spend exceeded the authorised cap")
        emit_json({"workdir": settings.workdir, "code": 4, "error": "committed spend exceeded the cap", "ledger": status})
        return 4

    if credential is not None:
        revoke_credential(settings)

    emit_json(
        {
            "workdir": settings.workdir,
            "code": 0,
            "revision": os.popen(f"git -C {REPO_ROOT} rev-parse HEAD").read().strip(),
            "mode": settings.mode,
            "authorization": authorization.to_dict(),
            "cap_worksheet": cap_worksheet(settings),
            "ledger": status,
            "trials": [
                {
                    "arm": trial.arm,
                    "seed": trial.seed,
                    "run_id": trial.run_id,
                    "classification": trial.classification,
                    "controller_outcome": trial.controller_outcome,
                    "total_cost": trial.total_cost,
                    "budget_exhaustion": trial.budget_exhaustion,
                }
                for trial in comparison.trials
            ],
        }
    )
    log("done. Review the authorisation, cap worksheet, spend ledger, and observability extract.")
    return 0


def probe(settings: Settings) -> int:
    """Issue exactly one model call through the configured client.

    This is the safest first real test: it validates the credential, transport,
    pricing, declared token ceilings, and accounting with a single billable
    call, before the four-arm comparison is ever run.
    """
    log(f"probe: one model call (mode={settings.mode})")
    workdir = os.path.join(settings.workdir, "probe")
    os.makedirs(workdir, mode=0o700, exist_ok=True)
    source = secrets.SecretsSource()
    if settings.mode == "real":
        factory, _credential = build_real_client_factory(settings, source)
        experiment.set_model_client_factory(factory)
    else:
        experiment.set_model_client_factory(None)
    experiment.set_secrets_source(source)
    try:
        run_id = "PROBE-1"
        db_path = os.path.join(workdir, "events.db")
        if os.path.exists(db_path):
            print(
                "      NOTE: the probe store already exists; use a fresh"
                " ORCHESTRATOR_WORKDIR for a new probe."
            )
            return 6
        store = EventStore(db_path)
        adapter = model_adapter_for(settings, settings.seeds[0])
        controller = Controller(
            store,
            ScriptedExecutor({}),
            model_executor=adapter,
            secrets_source=source,
            executor_environment={
                "base_commit": "HEAD",
                "timeout_seconds": float(settings.wall_seconds),
                "environment_version": experiment.ENVIRONMENT_VERSION,
            },
        )
        config = {
            "schema_version": 1,
            "run_id": run_id,
            "root_contract": {
                "description": "milestone-8 transport probe",
                "owned_scope": ["src/probe/**"],
                "acceptance_command": "true",
            },
            "executor_profile": "smoke-probe-v1",
            "budgets": {"MODEL_COST": settings.model_cost},
            "limits": {
                "root_model_input_tokens": settings.max_input_tokens,
                "root_model_output_tokens": settings.max_output_tokens,
                "model_calls": 1,
                "actions": 1,
                "nodes": 1,
                "maximum_depth": 0,
                "wall_clock_seconds": settings.wall_seconds,
            },
            "project_kernel": {
                "schema_version": 1,
                "kernel_id": "KERNEL-PROBE",
                "repository_commit": "HEAD",
                "frozen_at": "2000-01-01T00:00:00Z",
            },
            "experiment_manifest": {
                "schema_version": 1,
                "manifest_id": "MANIFEST-PROBE",
                "manifest_hash": "sha256:probe",
            },
            "policy_version": 1,
        }
        root = controller.submit_run(config)
        _attempt, response = controller.run_model_review(
            run_id, root, settings.per_attempt_commitment
        )
        report = response.get("cost_report", {})
        log("probe result")
        print(f"      self_reported_status : {response.get('self_reported_status')}")
        print(f"      committed            : {report.get('committed')}")
        print(f"      actual               : {report.get('actual')}")
        print(f"      units                : {report.get('units')}")
        print(f"      declared_max         : {report.get('declared_max')}")
        print(f"      model_usage          : {report.get('model_usage')}")
        print(f"      budget_exhausted     : {report.get('budget_exhausted')}")
        print(f"      ledger total_charged : {controller.get_costs(run_id)['total_charged']}")
        if report.get("budget_exhausted"):
            log("STOP: the single call overran its commitment (see actual vs committed)")
            store.close()
            emit_json({"mode": settings.mode, "code": 3, "budget_exhausted": True, "cost_report": report})
            return 3
        emit_json(
            {
                "mode": settings.mode,
                "code": 0,
                "status": response.get("self_reported_status"),
                "cost_report": report,
                "total_charged": controller.get_costs(run_id)["total_charged"],
            }
        )
        log("probe OK: one call, priced and accounted. The four-arm comparison is next.")
        store.close()
        return 0
    except (BudgetExhausted, spend.SpendCapExceeded) as error:
        log(f"STOP: {type(error).__name__}: {error}")
        emit_json({"mode": settings.mode, "code": 2, "error": str(error)})
        return 2
    except Exception as error:  # noqa: BLE001 - report the transport/provider failure
        log(f"probe FAILED: {type(error).__name__}: {error}")
        emit_json({"mode": settings.mode, "code": 7, "error": f"{type(error).__name__}: {error}"})
        return 7
    finally:
        if settings.mode == "real":
            revoke_credential(settings)
        experiment.set_model_client_factory(None)
        experiment.set_secrets_source(None)


def model_adapter_for(settings: Settings, seed: Optional[int] = None):
    from orchestrator.model_adapter import ModelAdapter

    profile = experiment.MODEL_PROFILE
    if settings.mode == "real":
        profile = experiment.ModelProfile(
            model_id=settings.provider_model,
            model_version=settings.provider_model_version,
            temperature=0.0,
            top_p=1.0,
            max_output_tokens=settings.max_output_tokens,
            input_tokens_per_call=settings.max_input_tokens,
            output_tokens_per_call=settings.max_output_tokens,
            cost_per_call=settings.per_attempt_commitment,
        )
        experiment.set_model_profile(profile)
    return ModelAdapter(
        experiment.model_client_for(profile, seed),
        model_id=profile.model_id,
        model_version=profile.model_version,
    )


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--inspect", action="store_true", help="print recorded state and exit")
    parser.add_argument("--resume", action="store_true", help="recover unfinished trials and exit")
    parser.add_argument(
        "--probe",
        action="store_true",
        help="issue exactly one model call (safest first real test) and exit",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="emit one JSON document on stdout; narration goes to stderr",
    )
    args = parser.parse_args()
    if args.json:
        global _JSON_MODE, _REAL_STDOUT
        _JSON_MODE = True
        _REAL_STDOUT = sys.stdout
        sys.stdout = sys.stderr
    settings = load_settings()
    if args.inspect:
        inspect(settings)
        return 0
    if args.resume:
        resume(settings)
        return 0
    validate(settings)
    if args.probe:
        return probe(settings)
    try:
        return run(settings)
    finally:
        experiment.set_model_client_factory(None)
        experiment.set_secrets_source(None)


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