# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-non-repudiation-receipts-when-a2a-delegation-crosses-a-key-rotation-boundary-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-non-repudiation-receipts-when-a2a-delegation-crosses-a-key-rotation-boundary-mid-task.warrant.json
# Markdown SHA-256:   80827c2af841c076c0dd3d102b293028ec1c376bbe78a5e0d3fca105a3cbaaf6
# Code AST SHA-256:   6a36eb8093d115e02c726756d77d6632b7d142d7b3cd3eb68d043261f414ef5c
# Verified Classes:   KeyContinuityBreach
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class KeyContinuityBreach(RuntimeError):
    """Raised when a completion receipt's signing key cannot be proven
    contiguous with the acceptance receipt's key under the agreed policy."""
    pass


def resolve_receipt(
    acceptance_key_id: str,
    completion_key_id: str,
    completion_signing_time: int,
    key_history: dict,
    agreed_policy: str,
) -> str:
    if agreed_policy != "contiguity-v1":
        # Policy disagreement is undetectable from receipts alone; refuse.
        raise KeyContinuityBreach(
            f"resolver policy {agreed_policy!r} does not match agreed 'contiguity-v1'"
        )

    entry = key_history.get(completion_key_id)
    if entry is None:
        return "UNKNOWN_SIGNING_KEY"

    start, end = entry["valid_from"], entry["valid_until"]
    if not (start <= completion_signing_time <= end):
        # Key existed but was not valid at the asserted signing time.
        raise KeyContinuityBreach(
            f"key {completion_key_id} invalid at t={completion_signing_time}"
        )

    acc = key_history.get(acceptance_key_id)
    if acc is None:
        raise KeyContinuityBreach(
            f"acceptance key {acceptance_key_id} absent from key history"
        )

    if completion_key_id == acceptance_key_id:
        return "ADMITTED_SAME_KEY"

    # Contiguity: new key's interval must begin at or before old key's end.
    if start <= acc["valid_until"]:
        return "ADMITTED_CONTIGUOUS_ROTATION"

    raise KeyContinuityBreach(
        f"gap between {acceptance_key_id} (ends {acc['valid_until']}) "
        f"and {completion_key_id} (starts {start})"
    )
