"""Reproducible local runtime drills and real-HTTP, real-worker synthetic load."""
import argparse
import copy
import hashlib
import json
import math
import os
import platform
import socket
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
from pathlib import Path

ROOT = Path(__file__).resolve().parent
ACTIVE_CHILDREN = set()
sys.path.insert(0, str(ROOT / "project"))
from agent import Agent
from common import LabError, MerchantClient, canonical, write_json
from store import Store
from runtime import Runtime, decide_settlement, load_student
from runtime_worker import perform
import merchant_runtime

ENGINEERING_FILES = ["runtime.sql", "runtime.py", "merchant_runtime.py", "runtime_worker.py", "senior_lab.py", "settlement_student.py", "test_runtime.py", "package.py",
    "project/agent.py", "project/common.py", "project/store.py", "project/model_adapter.py", "project/retrieval.py", "project/merchant_service.py",
    "project/migrations/001.sql", "project/migrations/002.sql", "project/SOURCE_PROVENANCE.json"]


def sources():
    return {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in ENGINEERING_FILES if (ROOT / name).is_file()}


def envelope(command, report):
    return {"format": "senior-runtime-evidence-v1", "command": command, "python": platform.python_version(),
        "pid": os.getpid(), "created_utc_seconds": time.time(), "model": "offline deterministic teaching adapter",
        "environment": "one host, one shared SQLite file per scenario, independent localhost HTTP merchant process",
        "scope": "fictional create_return application only; author-defined synthetic units; no provider usage or production capacity",
        "sources": sources(), "evidence": report}


def fresh(work):
    work = Path(work).resolve()
    if work.exists() and any(work.iterdir()):
        raise LabError("use_fresh_work_directory")
    work.mkdir(parents=True, exist_ok=True)
    return work


@contextmanager
def service(work, global_limit=2, tenant_limit=1, budget=1000):
    work = Path(work)
    work.mkdir(parents=True, exist_ok=True)
    path = work / "shared.sqlite"
    merchant_runtime.init(path, global_limit, tenant_limit, budget)
    with socket.socket() as sock:
        sock.bind(("127.0.0.1", 0))
        port = sock.getsockname()[1]
    process = subprocess.Popen([sys.executable, "-B", str(ROOT / "merchant_runtime.py"), "--db", str(path), "--port", str(port)],
                    stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"))
    url = f"http://127.0.0.1:{port}"
    try:
        deadline = time.monotonic() + 8
        while True:
            if process.poll() is not None:
                raise LabError("merchant_start_failed")
            try:
                with urllib.request.urlopen(url + "/health", timeout=.3) as response:
                    if json.load(response)["ok"]:
                        break
            except (OSError, ValueError):
                if time.monotonic() > deadline:
                    raise LabError("merchant_start_timeout")
                time.sleep(.02)
        yield url
    finally:
        for child in list(ACTIVE_CHILDREN):
            if child.poll() is None:
                child.terminate()
                try:
                    child.communicate(timeout=2)
                except subprocess.TimeoutExpired:
                    child.kill()
                    child.communicate()
            ACTIVE_CHILDREN.discard(child)
        process.terminate()
        try:
            process.communicate(timeout=3)
        except subprocess.TimeoutExpired:
            process.kill()
            process.communicate()


def prepare(work, url, task_id, tenant="acme"):
    token, order, reviewer = ("alice-token", "o-100", "reviewer-token") if tenant == "acme" else ("other-token", "o-other", "other-reviewer-token")
    store = Store(Path(work) / "tasks" / (task_id + ".sqlite"))
    try:
        agent = Agent(store, MerchantClient(url, token))
        task = agent.submit(order, "Return my unused ordinary item; it does not fit.", task_id)
        task = agent.run(task_id)
        if task["status"] != "awaiting_approval":
            raise AssertionError("actual_agent_proposal_required")
        task = Agent(store, MerchantClient(url, reviewer)).approve(task_id, 1, task["proposal_hash"])
        if task["status"] != "ready":
            raise AssertionError("actual_demo_reviewer_approval_required")
        runtime = Runtime(Path(work) / "shared.sqlite")
        try:
            runtime.enqueue(task_id, task["tenant"], task["owner"], task["operation_key"])
        finally:
            runtime.close()
        return {"task_id": task_id, "tenant": task["tenant"], "owner": task["owner"], "status": task["status"],
                "turn_count": task["turn_count"], "tool_count": task["tool_count"], "operation_key": task["operation_key"],
                "approval": "seeded fictional reviewer fixture; not a real human approval"}
    finally:
        store.close()


def launch(work, url, task_id=None, command="one", **options):
    args = [sys.executable, "-B", str(ROOT / "runtime_worker.py"), command, "--work", str(Path(work).resolve()), "--url", url]
    if task_id:
        args += ["--task-id", task_id]
    for key, value in options.items():
        flag = "--" + key.replace("_", "-")
        if value is True:
            args.append(flag)
        elif value is not None and value is not False:
            args += [flag, str(value)]
    process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
                              env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"))
    ACTIVE_CHILDREN.add(process)
    return process


def collect(process, expected=0):
    stdout, stderr = process.communicate(timeout=40)
    ACTIVE_CHILDREN.discard(process)
    report = {"pid": process.pid, "exit_code": process.returncode,
              "result": json.loads(stdout) if stdout.strip() else None, "stderr": stderr.strip()}
    if process.returncode != expected:
        raise AssertionError(report)
    return report


def wait_file(path, process):
    deadline = time.monotonic() + 8
    while not Path(path).exists():
        if time.monotonic() > deadline or process.poll() is not None:
            raise AssertionError("worker_barrier_not_reached")
        time.sleep(.01)
    return json.loads(Path(path).read_text())


def expect_code(fn, code):
    try:
        fn()
    except LabError as exc:
        if exc.code == code:
            return {"expected_error": code, "observed_error": exc.code}
        raise
    raise AssertionError("expected_rejection:" + code)


def ledger(runtime):
    return {"returns": [dict(r) for r in runtime.db.execute("SELECT * FROM returns ORDER BY task_id")],
            "receipts": [dict(r) | {"result": json.loads(r["result_json"])} for r in runtime.db.execute("SELECT * FROM receipts ORDER BY task_id")],
            "costs": [dict(r) for r in runtime.db.execute("SELECT * FROM rt_costs ORDER BY operation_key")]}


def payload(work, task_id, claim):
    store = Store(Path(work) / "tasks" / (task_id + ".sqlite"))
    try:
        task = store.get(task_id)
        return {"task_id": task_id, "proposal": task["proposal"], "proposal_hash": task["proposal_hash"],
            "approval_id": task["approval"]["approval_id"], "operation_key": task["operation_key"], "fence": 1,
            "runtime_epoch": claim["epoch"], "runtime_worker": claim["worker"], "runtime_reservation": claim["reservation_id"]}
    finally:
        store.close()


def expiry(runtime, task_id):
    remaining = runtime.task(task_id)["expires"] - time.time()
    if remaining > 2:
        raise AssertionError("drill_requires_bounded_short_lease")
    if remaining > 0:
        time.sleep(remaining + .025)


def demo(work):
    work = fresh(work)
    result = {}
    # Simultaneous held admission: acme limit rejects while other remains eligible;
    # then two actual PIDs overlap and a third attempt hits the global limit.
    place = work / "competition"
    with service(place) as url:
        prepared = [prepare(place, url, "acme-a"), prepare(place, url, "acme-b"), prepare(place, url, "other-a", "other")]
        barrier = place / "continue"
        first = launch(place, url, "acme-a", barrier=barrier)
        a = wait_file(str(barrier) + ".acme-a", first)
        denied_tenant = collect(launch(place, url, "acme-b"), expected=2)
        assert denied_tenant["result"]["error"] == "tenant_backpressure"
        second = launch(place, url, "other-a", barrier=barrier)
        b = wait_file(str(barrier) + ".other-a", second)
        denied_global = collect(launch(place, url, "acme-b"), expected=2)
        assert denied_global["result"]["error"] == "global_backpressure"
        runtime = Runtime(place / "shared.sqlite")
        overlap = runtime.snapshot()
        assert sum(t["reservation_id"] is not None for t in overlap["tasks"]) == 2
        barrier.write_text("continue\n")
        completed = [collect(first), collect(second), collect(launch(place, url, "acme-b"))]
        end = runtime.snapshot()
        assert all(t["state"] == "completed" for t in end["tasks"])
        assert all(r["reserved"] == 0 for r in end["budgets"])
        result["competition"] = {"prepared_actual_agent_tasks": prepared, "barrier_workers": [a, b], "simultaneous_reservations": overlap,
                    "tenant_denied": denied_tenant, "global_denied": denied_global, "completed_workers": completed, "final": end, "merchant_ledger": ledger(runtime)}
        runtime.close()
    # Real TCP response loss followed by os._exit(75); a second process retains the
    # original reservation and reconciles the same unique merchant operation key.
    place = work / "crash"
    with service(place) as url:
        prepared = prepare(place, url, "crash-return")
        crash = collect(launch(place, url, "crash-return", fault="crash", lease=.6), expected=75)
        runtime = Runtime(place / "shared.sqlite")
        before = runtime.snapshot()
        assert before["tasks"][0]["reservation_id"] and before["budgets"][0]["reserved"] == 5
        assert len(ledger(runtime)["receipts"]) == 1
        expiry(runtime, "crash-return")
        recovered = collect(launch(place, url, "crash-return", recover=True, lease=5))
        final = runtime.snapshot()
        assert final["tasks"][0]["epoch"] == 2 and final["tasks"][0]["state"] == "completed"
        assert len(ledger(runtime)["returns"]) == 1 and final["budgets"][0]["spent"] == 3
        result["crash"] = {"prepared_actual_agent_task": prepared, "worker_crash": crash, "before_restart": before,
                    "unresolved_lease_is_unknown_effect": True, "recover_worker": recovered, "final": final, "merchant_ledger": ledger(runtime)}
        runtime.close()
    place = work / "guards"
    with service(place, budget=10) as url:
        prepare(place, url, "guard-return")
        runtime = Runtime(place / "shared.sqlite")
        old = runtime.acquire("guard-return", "stale-old", seconds=.12)
        old_body = payload(place, "guard-return", old)
        MerchantClient(url, "alice-token").request("POST", "/v1/claims", {"task_id": "guard-return", "fence": 1})
        expiry(runtime, "guard-return")
        current = runtime.acquire("guard-return", "current", recover=True)
        stale_http = expect_code(lambda: MerchantClient(url, "alice-token").request("POST", "/v1/returns", old_body), "runtime_stale_claim")
        stale_local = expect_code(lambda: runtime.settle(old, "unknown"), "runtime_stale_claim")
        fake_reservation = dict(current, reservation_id="someone-elses-reservation")
        binding = expect_code(lambda: runtime.settle(fake_reservation, "unknown"), "runtime_stale_claim")
        fake_receipt = {"operation_key": runtime.task("guard-return")["operation_key"]}
        forged = expect_code(lambda: runtime.settle(current, "confirmed_receipt", 3, fake_receipt), "runtime_receipt_unconfirmed")
        runtime.revoke("acme", "alice")
        revoke_http = expect_code(lambda: MerchantClient(url, "alice-token").request("POST", "/v1/returns", payload(place, "guard-return", current)), "runtime_permission_denied")
        revoke_finish = expect_code(lambda: runtime.settle(current, "confirmed_absent"), "runtime_permission_denied")
        conserved = runtime.snapshot()
        assert conserved["budgets"][0]["reserved"] == 5 and not ledger(runtime)["returns"]
        # Explicit lab controller restores current authority; old epoch remains fenced.
        runtime.db.execute("UPDATE rt_acl SET active=1,revision=revision+1 WHERE tenant='acme' AND owner='alice'")
        released = runtime.settle(current, "confirmed_absent")
        no_late_write = expect_code(lambda: MerchantClient(url, "alice-token").request("POST", "/v1/returns", payload(place, "guard-return", current)), "runtime_stale_claim")
        assert released["state"] == "abandoned" and runtime.snapshot()["budgets"][0]["reserved"] == 0
        result["guards"] = {"old": old, "current": current, "stale_http": stale_http, "stale_local": stale_local, "reservation_binding": binding,
                "forged_receipt": forged, "revoked_http": revoke_http, "revoked_completion": revoke_finish, "revoked_conserves": conserved,
                "controller_restored_authority": True, "confirmed_absent_release": released, "post_release_http": no_late_write, "merchant_ledger": ledger(runtime)}
        runtime.close()
    return envelope("demo", result)


def nearest_rank(values, percentile):
    if not values:
        return None
    return sorted(values)[max(0, math.ceil(percentile * len(values)) - 1)]


def peak_events(snapshot):
    held, by_tenant, peak, tenant_peaks, budgets, budget_peaks = {}, {}, 0, {}, {}, {}
    task_tenants = {t["id"]: t["tenant"] for t in snapshot["tasks"]}
    for event in snapshot["events"]:
        value = event["value"]
        tenant = task_tenants.get(event["task_id"])
        if event["event"] == "admitted":
            held[event["task_id"]] = tenant
            budgets[tenant] = budgets.get(tenant, 0) + value["reserved_units"]
        elif event["event"] == "settlement":
            action = value["decision"]["action"]
            if action in {"settle", "release"}:
                held.pop(event["task_id"], None)
                # reserved + spent changes only by released units.
                budgets[tenant] -= value["decision"]["release_units"]
        by_tenant = {t: list(held.values()).count(t) for t in set(held.values())}
        peak = max(peak, len(held))
        for t, count in by_tenant.items():
            tenant_peaks[t] = max(tenant_peaks.get(t, 0), count)
        for t, units in budgets.items():
            budget_peaks[t] = max(budget_peaks.get(t, 0), units)
    return {"global_held_peak": peak, "tenant_held_peaks": tenant_peaks, "reserved_plus_spent_peaks": budget_peaks}


def load(work, tasks=12, workers=4):
    if type(tasks) is not int or not 2 <= tasks <= 30 or type(workers) is not int or not 2 <= workers <= 8:
        raise ValueError("bounded_load_requires_2_to_30_tasks_2_to_8_workers")
    work = fresh(work)
    with service(work, budget=100) as url:
        preparation_start = time.perf_counter_ns()
        prepared = [prepare(work, url, f"load-{index:03}", "acme" if index % 2 == 0 else "other") for index in range(tasks)]
        preparation_ns = time.perf_counter_ns() - preparation_start
        started_utc, started_ns = time.time(), time.perf_counter_ns()
        children = [launch(work, url, command="pool", worker_no=index) for index in range(workers)]
        reports = [collect(child) for child in children]
        finished_ns, finished_utc = time.perf_counter_ns(), time.time()
        runtime = Runtime(work / "shared.sqlite")
        snapshot, merchant = runtime.snapshot(), ledger(runtime)
        states = {name: sum(t["state"] == name for t in snapshot["tasks"]) for name in ["queued", "leased", "unknown", "overrun", "completed", "abandoned"]}
        terminal = [t for t in snapshot["tasks"] if t["terminal"] is not None]
        accepted = [t for t in snapshot["tasks"] if t["admitted"] is not None]
        successful = [t for t in terminal if t["state"] == "completed"]
        execution_latency = [(t["terminal"] - t["admitted"]) * 1000 for t in successful]
        end_to_end = [(t["terminal"] - t["submitted"]) * 1000 for t in successful]
        elapsed_seconds = (finished_ns - started_ns) / 1e9
        reject_attempts = {}
        for report in reports:
            for code, count in report["result"]["rejected_attempts"].items():
                reject_attempts[code] = reject_attempts.get(code, 0) + count
        peaks = peak_events(snapshot)
        assert states["completed"] == tasks and len(merchant["returns"]) == tasks and len(merchant["receipts"]) == tasks
        assert peaks["global_held_peak"] <= 2 and all(n <= 1 for n in peaks["tenant_held_peaks"].values())
        assert all(b["reserved"] == 0 and b["spent"] <= b["total"] for b in snapshot["budgets"])
        evidence = {"requested_tasks": tasks, "requested_workers": workers, "prepared_actual_agent_tasks": prepared,
            "preparation_seconds": preparation_ns / 1e9, "worker_window": {"started_utc_seconds": started_utc, "finished_utc_seconds": finished_utc,
                "started_perf_counter_ns": started_ns, "finished_perf_counter_ns": finished_ns, "elapsed_seconds": elapsed_seconds},
            "accounting": {"submitted": len(snapshot["tasks"]), "admitted_unique_tasks": len(accepted), "not_admitted_tasks": len(snapshot["tasks"])-len(accepted),
                "terminal": len(terminal), "successful": len(successful), "worker_errors": sum(r["state"] == "worker_error" for p in reports for r in p["result"]["results"]),
                "states": states, "rejected_admission_attempts": reject_attempts, "sum_states": sum(states.values())},
            "measured_throughput": {"successful_tasks_per_worker_window_second": len(successful)/elapsed_seconds,
                "denominator_tasks": len(successful), "denominator_seconds": elapsed_seconds},
            "latency_ms": {"algorithm": "nearest rank: sorted_values[ceil(p*n)-1]", "execution_success_n": len(execution_latency),
                "execution_from_admission_p50": nearest_rank(execution_latency, .5), "execution_from_admission_p95": nearest_rank(execution_latency, .95),
                "submitted_to_terminal_success_n": len(end_to_end), "submitted_to_terminal_p50": nearest_rank(end_to_end, .5), "submitted_to_terminal_p95": nearest_rank(end_to_end, .95),
                "accepted_nonterminal_n": len(accepted)-len(terminal), "all_accepted_completed_here": len(accepted)==len(successful)},
            "excluded_from_worker_window": ["initial SQLite setup", "actual offline Agent model/tools/RAG/proposal turns and seeded reviewer fixture approval"],
            "included_in_execution_latency": ["runtime admitted lease", "explicit 25ms local overlap pause", "actual original Agent.execute", "localhost HTTP receipt lookup/claims/write", "SQLite checkpoint and reservation settlement"],
            "interpretation": "Small local synthetic sample. Worker execution throughput excludes Agent preparation; submitted-to-terminal includes queue wait after preparation. No cloud, live-model latency, token usage, currency cost or multi-host capacity inference.",
            "peaks": peaks, "workers": reports, "final": snapshot, "merchant_ledger": merchant}
        runtime.close()
        return envelope("load", evidence)


def verify_learner(work, student):
    work = fresh(work)
    student = Path(student).resolve()
    try:
        decision = load_student(student)
    except Exception as exc:
        check_ids = [f"contract-valid-{i}" for i in range(8)] + [f"contract-invalid-{i}" for i in range(16)] + [
            "actual-hook-unknown-holds", "actual-hook-original-key-reconciles", "actual-hook-confirmed-absence-releases", "actual-hook-overrun-holds-and-freezes"]
        return envelope("verify-learner", {"student": {"path": student.name, "sha256": hashlib.sha256(student.read_bytes()).hexdigest() if student.is_file() else None},
            "checks": [{"id": name, "passed": False, "error": "student_import_failed", "execution": "blocked_by_import"} for name in check_ids],
            "import_error": {"type": type(exc).__name__, "message": "student_import_control_exit" if str(exc) == "student_import_control_exit" else "student_import_failed"},
            "passed": 0, "total": len(check_ids), "success": False, "actual_hooks_executed": False})
    checks = []

    def check(name, fn, contract_input=None, expected=None):
        detail = {"input": contract_input, "expected": expected} if contract_input is not None else {}
        try:
            observed = fn()
            checks.append({"id": name, "passed": True, **detail, "observed": observed})
        except Exception as exc:
            checks.append({"id": name, "passed": False, **detail, "error": getattr(exc, "code", type(exc).__name__)})

    def same(value, expected):
        supplied = copy.deepcopy(value)
        result = decision(supplied)
        assert supplied == value, "input_mutation"
        assert type(result) is dict and set(result) == {"action", "charge_units", "release_units"}, "output_keys"
        assert type(result["action"]) is str and type(result["charge_units"]) is int and type(result["release_units"]) is int, "output_types"
        assert result == expected, "output_decision"
        return result

    valid = [({"reserved_units": reserve, "actual_units": actual, "evidence": "confirmed_receipt"})
             for reserve, actual in [(1, 0), (5, 3), (5, 5), (5, 6)]]
    valid += [{"reserved_units": reserve, "actual_units": None, "evidence": evidence}
              for reserve in [1, 5] for evidence in ["unknown", "confirmed_absent"]]
    for index, value in enumerate(valid):
        # Public fixed expected cases specify the new contract, without publishing a new implementation.
        expected = {"action": "overrun", "charge_units": 6, "release_units": 0} if index == 3 else decide_settlement(value)
        check(f"contract-valid-{index}", lambda value=value, expected=expected: same(value, expected), copy.deepcopy(value), expected)
    invalid = [None, [], {}, {"reserved_units": True, "actual_units": None, "evidence": "unknown"},
        {"reserved_units": 0, "actual_units": None, "evidence": "unknown"}, {"reserved_units": 5.0, "actual_units": None, "evidence": "unknown"},
        {"reserved_units": 5, "actual_units": 0, "evidence": "unknown"}, {"reserved_units": 5, "actual_units": 0, "evidence": "confirmed_absent"},
        {"reserved_units": 5, "actual_units": None, "evidence": "confirmed_receipt"}, {"reserved_units": 5, "actual_units": True, "evidence": "confirmed_receipt"},
        {"reserved_units": 5, "actual_units": -1, "evidence": "confirmed_receipt"}, {"reserved_units": 5, "actual_units": 3.0, "evidence": "confirmed_receipt"},
        {"reserved_units": 5, "actual_units": None, "evidence": []}, {"reserved_units": 5, "actual_units": None, "evidence": {}},
        {"reserved_units": 5, "actual_units": None, "evidence": "UNKNOWN"}, {"reserved_units": 5, "actual_units": None, "evidence": "unknown", "extra": 1}]
    def rejected(value):
        supplied = copy.deepcopy(value)
        try:
            decision(supplied)
        except ValueError as exc:
            assert supplied == value, "input_mutation"
            assert str(exc) == "invalid_settlement_input"
            return {"exception": "ValueError", "message": str(exc)}
        raise AssertionError("must_raise_ValueError")
    for index, value in enumerate(invalid):
        check(f"contract-invalid-{index}", lambda value=value: rejected(value), copy.deepcopy(value), {"exception": "ValueError", "message": "invalid_settlement_input"})
    # Actual runtime hook with HTTP effect, followed by a real process restart recovery.
    place = work / "hook"
    with service(place, budget=12) as url:
        prepare(place, url, "student-return")
        runtime = Runtime(place / "shared.sqlite", decision)
        claim = runtime.acquire("student-return", "student-http", seconds=.7)
        try:
            # Dropped HTTP response is a genuine unknown. perform imports the student in the runtime.
            result = perform(place, url, claim, student=str(student), fault="drop")
            before = runtime.snapshot()
            def held():
                assert result["state"] == "unknown" and before["budgets"][0]["reserved"] == 5
                assert before["budgets"][0]["spent"] == 0 and len(ledger(runtime)["receipts"]) == 1
            check("actual-hook-unknown-holds", held)
        except Exception as exc:
            checks.append({"id": "actual-hook-unknown-holds", "passed": False, "error": getattr(exc, "code", type(exc).__name__)})
            before = runtime.snapshot()
        expiry(runtime, "student-return")
        child = launch(place, url, "student-return", student=str(student), recover=True, lease=5)
        stdout, stderr = child.communicate(timeout=30)
        final = runtime.snapshot()
        child_report = {"pid": child.pid, "exit_code": child.returncode, "result": json.loads(stdout) if stdout.strip() else None, "stderr": stderr.strip()}
        def reconciled():
            assert child.returncode == 0 and final["tasks"][0]["state"] == "completed"
            assert final["tasks"][0]["epoch"] == 2 and final["budgets"][0]["reserved"] == 0 and final["budgets"][0]["spent"] == 3
            assert len(ledger(runtime)["returns"]) == 1 and len(ledger(runtime)["receipts"]) == 1
        check("actual-hook-original-key-reconciles", reconciled)
        hook = {"before_restart": before, "recovery_worker": child_report, "final": final, "merchant_ledger": ledger(runtime)}
        runtime.close()
    # Confirmed-absent release also executes at the real runtime completion point.
    place = work / "absence"
    with service(place, budget=12) as url:
        prepare(place, url, "student-absent")
        runtime = Runtime(place / "shared.sqlite", decision)
        claim = runtime.acquire("student-absent", "student-absent")
        def absent():
            final = runtime.settle(claim, "confirmed_absent")
            assert final["state"] == "abandoned" and runtime.snapshot()["budgets"][0]["reserved"] == 0 and runtime.snapshot()["budgets"][0]["spent"] == 0
        check("actual-hook-confirmed-absence-releases", absent)
        absence = {"final": runtime.snapshot(), "merchant_ledger": ledger(runtime)}
        runtime.close()
    place = work / "overrun"
    with service(place, tenant_limit=2, budget=12) as url:
        prepare(place, url, "student-overrun")
        runtime = Runtime(place / "shared.sqlite", decision)
        claim = runtime.acquire("student-overrun", "student-overrun", reserve=2)
        def overrun():
            result = perform(place, url, claim, student=str(student))
            task = runtime.task("student-overrun")
            budget = runtime.snapshot()["budgets"][0]
            assert result["state"] == "overrun" and task["actual_units"] == 3 and task["reservation_id"] == claim["reservation_id"]
            assert budget["reserved"] == 2 and budget["spent"] == 0 and budget["frozen"] == 1
            prepare(place, url, "student-after-overrun")
            expect_code(lambda: runtime.acquire("student-after-overrun", "next-worker"), "tenant_budget_frozen")
        check("actual-hook-overrun-holds-and-freezes", overrun)
        overrun_report = {"final": runtime.snapshot(), "merchant_ledger": ledger(runtime)}
        runtime.close()
    report = envelope("verify-learner", {"student": {"path": student.name, "sha256": hashlib.sha256(student.read_bytes()).hexdigest()},
        "checks": checks, "passed": sum(x["passed"] for x in checks), "total": len(checks), "success": all(x["passed"] for x in checks),
        "actual_hook": hook, "actual_absence_hook": absence, "actual_overrun_hook": overrun_report,
        "scope": "Fixed public contract tests plus genuine runtime hook/HTTP/restart checks, not an enterprise hiring calibration."})
    return report


def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("command", choices=["demo", "load", "verify-learner"])
    parser.add_argument("--work", required=True)
    parser.add_argument("--tasks", type=int, default=12)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--student", default=str(ROOT / "settlement_student.py"))
    parser.add_argument("--out")
    args = parser.parse_args(argv)
    result = demo(args.work) if args.command == "demo" else load(args.work, args.tasks, args.workers) if args.command == "load" else verify_learner(args.work, args.student)
    out = Path(args.out) if args.out else Path(args.work) / "report.json"
    write_json(out, result)
    summary = {"command": args.command, "report": str(out), "status": "passed"}
    if args.command == "verify-learner":
        summary.update({k: result["evidence"][k] for k in ["passed", "total", "success"]})
        summary["status"] = "passed" if result["evidence"]["success"] else "failed"
    print(canonical(summary))
    return 1 if args.command == "verify-learner" and not result["evidence"]["success"] else 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except LabError as exc:
        print(canonical({"error": exc.code}), file=sys.stderr)
        sys.exit(2)
