# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-broker-witnessed-delegation-whose-policy-digest-it-cannot-re-derive-from-its-own-trust-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-broker-witnessed-delegation-whose-policy-digest-it-cannot-re-derive-from-its-own-trust-anchor.warrant.json
# Markdown SHA-256:   ab6636118e65357160193eeee367d4b6eafa9b1f5b7a5e78a1b37bd6edd2c1ee
# Code AST SHA-256:   f1bdb2e81ab96acbb9c6848f71ee204af8ceb9b41587120eb12121b89023a161
# Verified Classes:   UnderivableDelegationError, Warrant, PolicyStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class UnderivableDelegationError(RuntimeError):
    """Raised when an executor cannot re-derive a warrant's policy binding
    against its current policy state, and cannot prove absence of drift."""


@dataclass
class Warrant:
    task_id: str
    delegator: str
    executor: str
    policy_digest: str          # sha256 hex the broker signed
    transcript_hash: str
    issued_at: float            # epoch seconds
    broker_sig: str


@dataclass
class PolicyStore:
    """Executor-local policy state with a change log."""
    constraints: dict           # name -> value
    change_log: list            # list of (timestamp, constraint_name, old, new)

    def digest(self, scope: list) -> str:
        canon = ";".join(f"{k}={self.constraints[k]}" for k in sorted(scope))
        return hashlib.sha256(canon.encode()).hexdigest()

    def changed_since(self, ts: float, scope: list) -> bool:
        return any(t > ts and name in scope for (t, name, _, _) in self.change_log)


def verify_and_admit(
    warrant: Warrant,
    store: PolicyStore,
    scope: list,
    transcript: Optional[dict],       # present iff executor holds it (condition D)
    delta_refresh: Optional[float],  # broker-published staleness bound (condition F)
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    # Cryptographic checks are necessary but never sufficient.
    if not warrant.broker_sig:
        raise UnderivableDelegationError(
            f"warrant {warrant.task_id}: missing broker signature"
        )

    # Condition (D): can we re-derive the digest from our own current state?
    if transcript is not None:
        recomputed = store.digest(scope)
        if recomputed == warrant.policy_digest:
            return  # derivable and matching: safe to execute
        # Derivable but mismatched: drift or attack, indistinguishable.
        raise UnderivableDelegationError(
            f"warrant {warrant.task_id}: policy digest mismatch "
            f"(warrant={warrant.policy_digest[:12]}, "
            f"local={recomputed[:12]}); cannot distinguish drift from attack"
        )

    # Condition (F): no transcript, fall back to freshness + no-drift proof.
    if delta_refresh is None:
        raise UnderivableDelegationError(
            f"warrant {warrant.task_id}: no transcript and no published "
            f"delta_refresh; cannot establish derivability or freshness"
        )
    if now - warrant.issued_at > delta_refresh:
        raise UnderivableDelegationError(
            f"warrant {warrant.task_id}: stale by "
            f"{now - warrant.issued_at - delta_refresh:.0f}s beyond "
            f"delta_refresh; escalate for re-negotiation"
        )
    if store.changed_since(warrant.issued_at, scope):
        raise UnderivableDelegationError(
            f"warrant {warrant.task_id}: local policy changed in scope "
            f"since issuance; witnessed form no longer valid, escalate"
        )
    # No change in scope, within freshness window: (F) holds.
    return
