# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-agent-card-whose-capability-manifest-was-re-signed-under-a-rotated-key-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-agent-card-whose-capability-manifest-was-re-signed-under-a-rotated-key-mid-delegation.warrant.json
# Markdown SHA-256:   9be146f9529effcc912a3c771e12def00ec082f2e3fd673f8f09d6d9a67a39ee
# Code AST SHA-256:   d44b53483be8de7b0c9a34d074e3810a84ef5f80f782a4445fc79a2309f45aea
# Verified Classes:   DelegationBindingError, ContinuationToken, LifecycleEvent
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DelegationBindingError(RuntimeError):
    """Raised when a lifecycle event's signer/manifest pair diverges from the
    pair frozen in the task's continuation token."""


@dataclass(frozen=True)
class ContinuationToken:
    task_id: str
    signer_kid: str
    manifest_hash: str


@dataclass(frozen=True)
class LifecycleEvent:
    task_id: str
    signer_kid: str
    manifest_hash: str
    signature_valid: bool


def validate_lifecycle_event(token: ContinuationToken, event: LifecycleEvent) -> None:
    if event.task_id != token.task_id:
        raise DelegationBindingError(
            f"task id mismatch: token={token.task_id} event={event.task_id}"
        )
    if not event.signature_valid:
        raise DelegationBindingError("event signature failed verification")

    signer_ok = event.signer_kid == token.signer_kid
    manifest_ok = event.manifest_hash == token.manifest_hash

    if signer_ok and manifest_ok:
        return  # continuation is bound; proceed

    if signer_ok and not manifest_ok:
        raise DelegationBindingError(
            "manifest mutated under stable key; treat as tampering or "
            "unconsented renegotiation"
        )
    if manifest_ok and not signer_ok:
        raise DelegationBindingError(
            f"signer rotated mid-task: token={token.signer_kid} "
            f"event={event.signer_kid}; binding broken even though manifest bytes match"
        )
    raise DelegationBindingError(
        "full renegotiation required: re-run discovery, diff warrants, "
        "require explicit caller consent before importing new authority"
    )


def manifest_hash(capabilities: list[str], warrant_scope: str) -> str:
    payload = "|".join(sorted(capabilities)) + "::" + warrant_scope
    return hashlib.sha256(payload.encode()).hexdigest()


if __name__ == "__main__":
    m1 = manifest_hash(["summarize", "extract"], "read-only")
    m2 = manifest_hash(["extract", "summarize"], "read-write")
    token = ContinuationToken("T-441", "K1", m1)

    # worker-3 rotated K1->K2 and widened warrant; event verifies under K2
    rotated = LifecycleEvent("T-441", "K2", m2, signature_valid=True)
    validate_lifecycle_event(token, rotated)  # raises
