# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-staleness-in-cross-org-agent-federation-the-warrant-epoch-skew-failure-in-policy-mediated-a2a-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-staleness-in-cross-org-agent-federation-the-warrant-epoch-skew-failure-in-policy-mediated-a2a-handoffs.warrant.json
# Markdown SHA-256:   62e9dea7f6dcb587724cfde56adb38b36c81eeccc1a9026d2fde1a02a433cccd
# Code AST SHA-256:   3c53e38e6f2b6bf9cf01d801ec371cde978c2cfbea8369001769c9fb60494561
# Verified Classes:   WarrantEpochSkewError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class WarrantEpochSkewError(RuntimeError):
    """Raised when a federated warrant is validated against a trust-anchor
    epoch other than the one under which it was minted."""
    pass


def admit_federated_warrant(warrant: dict, anchor_store: dict) -> dict:
    """
    Admit a cross-org warrant with strict epoch pinning.

    warrant: {
        "anchor_epoch": int,      # epoch at mint time (set by delegator)
        "payload_epoch": int,     # epoch the planner used to generate instructions
        "signature": str,
        "scope": str,
    }
    anchor_store: {epoch: {"root_key": str, "scope_rules": dict}}
    """
    mint_epoch = warrant.get("anchor_epoch")
    payload_epoch = warrant.get("payload_epoch")

    # Invariant 1: envelope and payload must agree on epoch.
    if mint_epoch != payload_epoch:
        raise WarrantEpochSkewError(
            f"payload generated under epoch {payload_epoch} but warrant "
            f"minted under {mint_epoch}; planner context diverged from envelope"
        )

    # Invariant 2: the mint epoch must be retrievable. No latest-anchor fallback.
    if mint_epoch not in anchor_store:
        raise WarrantEpochSkewError(
            f"historical anchor bundle for epoch {mint_epoch} unavailable; "
            f"refusing to validate against latest anchor (fail closed)"
        )

    pinned_anchor = anchor_store[mint_epoch]

    # Invariant 3: validate signature against the pinned root, not current root.
    if not _verify_chain(warrant["signature"], pinned_anchor["root_key"]):
        raise WarrantEpochSkewError(
            f"signature does not chain to root of epoch {mint_epoch}"
        )

    # Invariant 4: apply scope rules from the mint epoch, never current rules.
    effective = _apply_scope_rules(warrant["scope"], pinned_anchor["scope_rules"])
    return {
        "effective_scope": effective,
        "validated_epoch": mint_epoch,
        "skew_checked": True,
    }


def _verify_chain(signature: str, root_key: str) -> bool:
    # Placeholder for real signature-chain verification.
    return signature.startswith(root_key)


def _apply_scope_rules(scope: str, rules: dict) -> str:
    return rules.get(scope, scope)
