# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-the-agent-card-snapshot-invariant-when-a2a-v1-0-task-delegation-crosses-an-org-boundary-mid-lifecycle.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-the-agent-card-snapshot-invariant-when-a2a-v1-0-task-delegation-crosses-an-org-boundary-mid-lifecycle.warrant.json
# Markdown SHA-256:   61a8266b7efc6b93e2c62414ceb3066d68d9e5bf4c6272d019b2cfc5657c4faf
# Code AST SHA-256:   44408fb19c454b6d3439aa6e4d37218641dcad59a3e6f57a31176bc491139fa8
# Verified Classes:   CardSnapshotMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CardSnapshotMismatch(RuntimeError):
    """Raised when a resumed A2A task's cached card snapshot no longer
    authorizes continuation against the remote's current card."""
    pass


AUTH_RELEVANT_FIELDS = ("securitySchemes", "skills", "endpoint", "capabilities")


def resume_task(cached_card: dict, task_id: str, skill_id: str, sign_fn) -> dict:
    # 1. Attempt continuation with cached credential.
    resp = _post(cached_card["endpoint"], {
        "taskId": task_id,
        "auth": sign_fn(cached_card["securitySchemes"]["kid"]),
    })
    if resp.status not in (401, 403):
        return resp

    # 2. Auth failure: re-fetch card, compare auth-relevant fields.
    fresh = _get_well_known(cached_card["endpoint"])
    for field in AUTH_RELEVANT_FIELDS:
        if fresh.get(field) != cached_card.get(field):
            # Authorization basis changed mid-lifecycle.
            if skill_id not in [s["id"] for s in fresh.get("skills", [])]:
                raise CardSnapshotMismatch(
                    f"skill {skill_id} revoked between discovery and resume "
                    f"of task {task_id}; aborting continuation"
                )
            if fresh.get("endpoint") != cached_card.get("endpoint"):
                raise CardSnapshotMismatch(
                    f"endpoint migrated for task {task_id}; "
                    f"taskId not portable across endpoints"
                )
            # Same endpoint, skill still present, only key rotated: re-sign once.
            new_kid = fresh["securitySchemes"]["kid"]
            resp = _post(fresh["endpoint"], {
                "taskId": task_id,
                "auth": sign_fn(new_kid),
            })
            if resp.status in (401, 403):
                raise CardSnapshotMismatch(
                    f"re-signed under kid={new_kid} still rejected for {task_id}"
                )
            return resp

    # Auth-relevant fields identical but still 401: credential itself is bad.
    raise CardSnapshotMismatch(
        f"card unchanged but continuation of {task_id} rejected; "
        f"credential invalid, not a snapshot issue"
    )
