# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-a-delegation-receipt-before-the-sub-agent-s-tool-side-effects-become-irreversible-and-what-breaks-when-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-a-delegation-receipt-before-the-sub-agent-s-tool-side-effects-become-irreversible-and-what-breaks-when-it-doesn-t.warrant.json
# Markdown SHA-256:   dd0f390ee81a542c58f0acae86a947c6942c73e12b7e58a1a220f4779138ab6f
# Code AST SHA-256:   bc1b9fea7b024c09063b35345b15e600422dc23b47fa6e56ecd388b22fa0e042
# Verified Classes:   DelegationReceiptError, Warrant, Attestation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class DelegationReceiptError(RuntimeError):
    """Raised when a delegation receipt cannot be bound to an authorization."""
    pass


@dataclass
class Warrant:
    delegator_id: str
    delegatee_id: str
    nonce: str
    scheme_id: str            # pins canonicalization; verifier MUST honor this
    typed_constraints: dict   # machine-checkable: {"amount_max": 50.00, "tool": "issue_refund"}
    prose_intent: str         # hint only; never authoritative for execution

    def canonical(self) -> bytes:
        # scheme_id selects the canonicalization; do not silently upgrade.
        if self.scheme_id != "cf-canon-v1":
            raise DelegationReceiptError(f"unknown canonicalization scheme: {self.scheme_id}")
        payload = {
            "delegator": self.delegator_id,
            "delegatee": self.delegatee_id,
            "nonce": self.nonce,
            "constraints": self.typed_constraints,
        }
        return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()

    def task_hash(self) -> str:
        return hashlib.sha256(self.canonical()).hexdigest()


@dataclass
class Attestation:
    """Sub-agent's signed statement of concrete parameters BEFORE side effect."""
    task_hash: str
    concrete_params: dict
    scheme_id: str

    def hash(self) -> str:
        payload = json.dumps(
            {"task": self.task_hash, "params": self.concrete_params, "scheme": self.scheme_id},
            sort_keys=True, separators=(",", ":"),
        ).encode()
        return hashlib.sha256(payload).hexdigest()


def validate_attestation(warrant: Warrant, att: Attestation) -> None:
    if att.task_hash != warrant.task_hash():
        raise DelegationReceiptError("attestation bound to a different warrant hash")
    if att.scheme_id != warrant.scheme_id:
        raise DelegationReceiptError("attestation canonicalization scheme mismatch")

    # Constraints must be checked against concrete params, not prose.
    for key, bound in warrant.typed_constraints.items():
        if key == "tool":
            if att.concrete_params.get("tool") != bound:
                raise DelegationReceiptError(
                    f"tool mismatch: authorized {bound!r}, attested {att.concrete_params.get('tool')!r}"
                )
            continue
        if key.endswith("_max"):
            field_name = key[: -len("_max")]
            actual = att.concrete_params.get(field_name)
            if actual is None:
                raise DelegationReceiptError(f"attestation missing required field {field_name!r}")
            if actual > bound:
                raise DelegationReceiptError(
                    f"scope expansion: {field_name}={actual} exceeds authorized max {bound}"
                )

    # Any constraint not expressible in the typed schema is a boundary escape.
    prose_only = set(warrant.typed_constraints) - {"tool"} - {
        k for k in warrant.typed_constraints if k.endswith("_max")
    }
    if prose_only:
        raise DelegationReceiptError(
            f"untyped constraints cannot be receipted: {sorted(prose_only)}"
        )


def commit_delegation(warrant: Warrant, att: Attestation) -> str:
    """Returns a COMMIT token the sub-agent must present to execute."""
    validate_attestation(warrant, att)
    return hashlib.sha256((att.hash() + warrant.nonce).encode()).hexdigest()
