# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-aaif-credential-mid-handoff-attestation-binding-divergence-between-the-signed-warrant-and-the-live-runtime.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-aaif-credential-mid-handoff-attestation-binding-divergence-between-the-signed-warrant-and-the-live-runtime.warrant.json
# Markdown SHA-256:   7e8ef7e2a12fc0fbfe88836d8865cdaf991b80131f7d3fa297cb8bac21f95bc1
# Code AST SHA-256:   5d710e5fab5522810384db6db224707a42f58a55befbfd16ac18e8098c6499b3
# Verified Classes:   AttestationBindingError, AAIFCredential, RuntimeBinding, HandoffEnvelope
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class AttestationBindingError(RuntimeError):
    """Raised when a runtime's live signing key diverges from the key
    embedded in the AAIF credential it presents at a handoff."""
    pass


@dataclass
class AAIFCredential:
    instance_id: str
    public_key_fingerprint: str   # fingerprint of the key the credential claims
    capability_set: frozenset
    warrant_scope: str
    not_before: float
    expires_at: float
    issuer_signature_valid: bool = True


@dataclass
class RuntimeBinding:
    instance_id: str
    live_key_fingerprint: str     # fingerprint of the key the process actually holds
    loaded_capabilities: frozenset
    spawned_at: float
    recycled: bool = False


@dataclass
class HandoffEnvelope:
    task_id: str
    from_instance: str
    to_instance: str
    segment: int
    envelope_signature_key_fp: str  # key that actually signed this frame
    payload_digest: str
    created_at: float = field(default_factory=time.time)


def fingerprint(key_material: bytes) -> str:
    return hashlib.sha256(key_material).hexdigest()[:16]


def verify_handoff_binding(
    cred: AAIFCredential,
    runtime: RuntimeBinding,
    envelope: HandoffEnvelope,
    now: Optional[float] = None,
) -> None:
    """Enforce the binding invariant: the key that signed the envelope must be
    the key the credential claims, and the credential must describe the live
    runtime. Any mismatch is a divergence and must quarantine, not retry."""
    now = now if now is not None else time.time()

    # 1. Credential must be temporally valid.
    if not (cred.not_before <= now <= cred.expires_at):
        raise AttestationBindingError(
            f"credential for {cred.instance_id} outside validity window"
        )
    if not cred.issuer_signature_valid:
        raise AttestationBindingError(
            f"credential for {cred.instance_id} has invalid issuer signature"
        )

    # 2. Attestation and binding must name the same instance.
    if cred.instance_id != runtime.instance_id:
        raise AttestationBindingError(
            f"credential instance {cred.instance_id} != runtime {runtime.instance_id}"
        )

    # 3. THE INVARIANT: envelope signer == credential-claimed key.
    #    Checking the registry instead of this is the silent-divergence bug.
    if envelope.envelope_signature_key_fp != cred.public_key_fingerprint:
        raise AttestationBindingError(
            f"divergent instance {cred.instance_id}: credential claims key "
            f"{cred.public_key_fingerprint}, envelope signed by "
            f"{envelope.envelope_signature_key_fp}; quarantine runtime, "
            f"resume task {envelope.task_id} from last durable checkpoint"
        )

    # 4. Runtime must actually hold the key the credential claims.
    if runtime.live_key_fingerprint != cred.public_key_fingerprint:
        raise AttestationBindingError(
            f"divergent runtime {runtime.instance_id}: live key "
            f"{runtime.live_key_fingerprint} != credential key "
            f"{cred.public_key_fingerprint}"
        )

    # 5. Capability set must not have drifted between attestation and binding.
    if not cred.capability_set.issubset(runtime.loaded_capabilities):
        raise AttestationBindingError(
            f"capability drift on {cred.instance_id}: credential grants "
            f"{cred.capability_set}, runtime loaded {runtime.loaded_capabilities}"
        )

    # 6. Warrant scope must cover the task being handed off.
    if cred.warrant_scope != f"task:{envelope.task_id}":
        raise AttestationBindingError(
            f"warrant scope {cred.warrant_scope} does not cover task "
            f"{envelope.task_id}"
        )


def handle_handoff(
    cred: AAIFCredential,
    runtime: RuntimeBinding,
    envelope: HandoffEnvelope,
) -> str:
    """Accept or quarantine. Never retry a divergent instance: retrying burns
    the sender's budget and loses un-checkpointed work."""
    try:
        verify_handoff_binding(cred, runtime, envelope)
    except AttestationBindingError as e:
        # Quarantine path: recycle the runtime, notify the task owner to resume
        # from the last durable checkpoint, and log as an identity event.
        runtime.recycled = True
        return f"QUARANTINE:{envelope.from_instance}:{e}"
    return f"ACCEPT:{envelope.task_id}:seg{envelope.segment}"


# --- reproduction of the observed failure ---
if __name__ == "__main__":
    now = time.time()

    # Runtime spawned with K1, never hot-swapped.
    k1_fp = fingerprint(b"key-material-K1")
    runtime = RuntimeBinding(
        instance_id="w-7f3a",
        live_key_fingerprint=k1_fp,
        loaded_capabilities=frozenset({"read_fs", "exec_sandbox", "emit_result"}),
        spawned_at=now - 640,
    )

    # Credential rotated at +600s: same id, new key K2.
    k2_fp = fingerprint(b"key-material-K2")
    rotated_cred = AAIFCredential(
        instance_id="w-7f3a",
        public_key_fingerprint=k2_fp,
        capability_set=frozenset({"read_fs", "exec_sandbox", "emit_result"}),
        warrant_scope="task:T-4419",
        not_before=now - 640,
        expires_at=now + 260,
    )

    # Handoff envelope signed by the key the runtime still holds (K1).
    envelope = HandoffEnvelope(
        task_id="T-4419",
        from_instance="w-7f3a",
        to_instance="a-2b1c",
        segment=2,
        envelope_signature_key_fp=k1_fp,
        payload_digest="sha256:deadbeef",
    )

    outcome = handle_handoff(rotated_cred, runtime, envelope)
    print(outcome)  # QUARANTINE:w-7f3a: divergent instance ... quarantine runtime
