# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-signature-capability-manifest-during-a2a-v1-0-card-discovery-when-the-signing-key-rotates-mid-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-signature-capability-manifest-during-a2a-v1-0-card-discovery-when-the-signing-key-rotates-mid-reconciliation.warrant.json
# Markdown SHA-256:   ff84c9f160b60f1699997c191c1c7d304f10bba56a6da7481951e1a976154f4c
# Code AST SHA-256:   c19105c62dfac68eb452770598ed67d175c6b1ff022a65585bac694784af6d26
# Verified Classes:   KeyEpochDriftError, SignedManifest, TaskContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass


class KeyEpochDriftError(RuntimeError):
    """Raised when a TaskStatus frame is signed under a key epoch that does not
    match the manifest generation the task was dispatched under."""


@dataclass(frozen=True)
class SignedManifest:
    key_id: str
    valid_until: float
    reconcile_mode: str          # "authoritative" | "advisory"
    supports_cancel: bool


@dataclass(frozen=True)
class TaskContract:
    task_id: str
    dispatched_manifest: SignedManifest
    dispatched_at: float


def reconcile_status_frame(
    contract: TaskContract,
    frame_key_id: str,
    frame_manifest: SignedManifest,
    frame_state: str,
    local_state: str,
    now: float | None = None,
) -> str:
    """Merge a peer TaskStatus frame into the local ledger, but only if the
    frame's signing key epoch and effective manifest generation match the
    contract frozen at dispatch. Returns the merged state."""
    now = now if now is not None else time.time()

    # Guard 1: manifest must still be within its declared validity window.
    if now > contract.dispatched_manifest.valid_until:
        raise KeyEpochDriftError(
            f"task {contract.task_id}: dispatched manifest expired at "
            f"{contract.dispatched_manifest.valid_until}, now {now}"
        )

    # Guard 2: the frame must be signed under the SAME key epoch the task
    # was dispatched under. A rotated key means the peer's capability
    # assertions may have changed underneath us.
    if frame_key_id != contract.dispatched_manifest.key_id:
        raise KeyEpochDriftError(
            f"task {contract.task_id}: frame signed under {frame_key_id!r} "
            f"but dispatched under {contract.dispatched_manifest.key_id!r}; "
            "refusing to merge across key-rotation boundary"
        )

    # Guard 3: even under the same keyId, the effective manifest body must
    # match. Catches re-issuance under a stable keyId with mutated content.
    if frame_manifest != contract.dispatched_manifest:
        raise KeyEpochDriftError(
            f"task {contract.task_id}: manifest body changed under stable "
            f"keyId {frame_key_id!r}; reconcile semantics not frozen"
        )

    # Safe to merge under the frozen contract.
    if contract.dispatched_manifest.reconcile_mode == "authoritative":
        return frame_state
    # advisory: local ledger wins on conflict
    return local_state if local_state != frame_state else frame_state
