# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-signed-agent-card-trust-from-being-silently-downgraded-during-a2a-v1-0-task-lifecycle-renegotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-signed-agent-card-trust-from-being-silently-downgraded-during-a2a-v1-0-task-lifecycle-renegotiation.warrant.json
# Markdown SHA-256:   ba8302a531703070b0e29ba7cb991bbcdaf44aeedbd0a724a0d7a721d8c32ce7
# Code AST SHA-256:   1eefa966bda63b4556f9f3362cfcfecf6ab0eb5e83bdc24df793ca08ccb33dfe
# Verified Classes:   TrustAnchorSubstitutionError, CapabilityWideningError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TrustAnchorSubstitutionError(RuntimeError):
    """Raised when a lifecycle card update would change the task's trust anchor
    without an explicit, pre-declared delegation or a re-admission transition."""


class CapabilityWideningError(RuntimeError):
    """Raised when a card update would expand the effective capability set
    for an in-flight task; widening requires re-admission, not update."""


def apply_card_update(task, update, verified_issuer, declared_delegates):
    # Invariant 1: issuer continuity. The update must be signed by the same
    # principal that admitted the task, OR that principal must have pre-declared
    # the new issuer as a delegate in its own signed card.
    if verified_issuer != task.admitting_issuer:
        if verified_issuer not in declared_delegates:
            raise TrustAnchorSubstitutionError(
                f"task {task.id}: card update signed by {verified_issuer!r} "
                f"but task was admitted under {task.admitting_issuer!r} "
                f"with no pre-declared delegation; refusing in-place update"
            )
        task.record_event("issuer_delegated", from_=task.admitting_issuer,
                          to=verified_issuer)

    # Invariant 2: monotonic capability set. Intersect, never union.
    new_caps = set(update.capabilities)
    widened = new_caps - task.effective_capabilities
    if widened:
        raise CapabilityWideningError(
            f"task {task.id}: update widens capabilities by {sorted(widened)}; "
            f"widening requires re-admission under a new task id"
        )
    task.effective_capabilities &= new_caps

    task.record_event("card_update_applied",
                      issuer=verified_issuer,
                      card_version=update.card_version)
    return task
