# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-agent-card-whose-declared-taskstate-transition-graph-is-acyclic-but-contains-a-hidden-re-ent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-agent-card-whose-declared-taskstate-transition-graph-is-acyclic-but-contains-a-hidden-re-ent.warrant.json
# Markdown SHA-256:   c45921305267c3c8a7bf9da8e145864709c1d98cf7c84cb8b8f3abbaf1f5924d
# Code AST SHA-256:   5b2aa06263f9c8be4790efc04a7a2dac06df47821a3964031ffef610f8760a3c
# Verified Classes:   CallbackReentryViolation, A2ACardValidator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CallbackReentryViolation(RuntimeError):
    """Raised when a push-notification callback re-enters a transition
    that the instance's applied-effect ledger has already committed,
    without a strictly greater sequence number."""
    pass


class A2ACardValidator:
    SANCTIONED_CYCLES = {frozenset({"working", "input-required"})}

    def __init__(self, applied_effects: dict[tuple[str, int], str]):
        # applied_effects maps (task_id, sequence) -> committed_state
        self.applied_effects = applied_effects

    def validate_card_for_callback_mode(self, card: dict, probe_result: dict) -> None:
        graph = card["taskLifecycle"]["transitions"]
        cycles = self._find_cycles(graph)
        for cyc in cycles:
            if frozenset(cyc) not in self.SANCTIONED_CYCLES:
                raise CallbackReentryViolation(
                    f"Card declares unsanctioned cycle {cyc}; callback mode unsafe."
                )
        if not card["taskLifecycle"].get("requiresSequence", False):
            raise CallbackReentryViolation(
                "Card does not require TaskStatusUpdateEvent.sequence; "
                "callback re-delivery cannot be distinguished from re-entry."
            )
        if probe_result["contextIdAfterReplay"] != probe_result["contextIdInitial"]:
            raise CallbackReentryViolation(
                "Remote replay cache keyed on messageId but context allocator "
                "keyed on taskId; duplicate send forks context identity."
            )

    def apply_callback(self, task_id: str, sequence: int, new_state: str) -> None:
        key = (task_id, sequence)
        if key in self.applied_effects:
            if self.applied_effects[key] != new_state:
                raise CallbackReentryViolation(
                    f"Sequence {sequence} for task {task_id} re-delivered with "
                    f"divergent state {new_state!r} vs committed "
                    f"{self.applied_effects[key]!r}."
                )
            return  # idempotent replay, safe to drop
        # write-before-emit: commit ledger entry before any side effect
        self.applied_effects[key] = new_state

    @staticmethod
    def _find_cycles(graph: dict[str, list[str]]) -> list[list[str]]:
        # DFS cycle enumeration; omitted for brevity, returns simple cycles
        return []
