# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-its-aaif-credential-after-a-context-compaction-and-silently-re-binds-to-a-stale-subject-key.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-its-aaif-credential-after-a-context-compaction-and-silently-re-binds-to-a-stale-subject-key.warrant.json
# Markdown SHA-256:   74eded47120879de6ebd4d4dfc26136454edb327f901ed226f1827eb25cc6ad8
# Code AST SHA-256:   1e01765173ee5eb94df4d4c612b6e91f69b7cdc1d76725635a9d34e18e576629
# Verified Classes:   AAIFBindingError
# Defensive Guards:   5 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

class AAIFBindingError(RuntimeError):
    """Raised when an agent's credential binding cannot be reconciled with live keystore state."""
    pass


def reattest_after_compaction(
    summarized_identity: dict,
    keystore_default_key_fingerprint: str,
    credential_subject_fingerprint: str,
    did_active_fingerprints: set,
) -> str:
    """
    Reconcile a post-compaction identity block against live state before attesting.

    Returns the fingerprint that MUST be used as the signing key, or raises.
    The summarized fingerprint is treated as a hint only; it is never used
    as input to a signing decision.
    """
    hint = summarized_identity.get("subject_key_fingerprint")

    # Invariant 1: the live keystore key must equal the credential's named subject key.
    if keystore_default_key_fingerprint != credential_subject_fingerprint:
        raise AAIFBindingError(
            "binding mismatch: keystore default key "
            f"{keystore_default_key_fingerprint} != credentialSubject key "
            f"{credential_subject_fingerprint}; refusing to attest and "
            "requesting re-issuance"
        )

    # Invariant 2: the credential's subject key must be active in the DID document.
    if credential_subject_fingerprint not in did_active_fingerprints:
        raise AAIFBindingError(
            f"credentialSubject key {credential_subject_fingerprint} is not "
            "active in the resolved DID document"
        )

    # Invariant 3: a stale hint that disagrees with live state is a reconciliation
    # event, not a silent override. Surface it so the caller can re-read state.
    if hint is not None and hint != credential_subject_fingerprint:
        raise AAIFBindingError(
            f"stale identity hint {hint} disagrees with live binding "
            f"{credential_subject_fingerprint}; compaction summary predates "
            "key rotation, re-read keystore and DID before proceeding"
        )

    return credential_subject_fingerprint


def verify_presentation(
    signing_key_fingerprint: str,
    credential_subject_fingerprint: str,
    did_active_fingerprints: set,
    cached_acceptance: dict | None = None,
) -> dict:
    """Verifier-side check: enforce binding equality, not set membership."""
    if signing_key_fingerprint != credential_subject_fingerprint:
        raise AAIFBindingError(
            "presentation rejected: proof-of-possession key "
            f"{signing_key_fingerprint} does not equal credentialSubject key "
            f"{credential_subject_fingerprint}; set-membership against "
            f"{sorted(did_active_fingerprints)} is insufficient"
        )
    if signing_key_fingerprint not in did_active_fingerprints:
        raise AAIFBindingError(
            f"signing key {signing_key_fingerprint} not active in DID document"
        )
    # Cache entries must carry the fingerprint that grounded them so that
    # revocation can invalidate by fingerprint rather than by re-verification.
    return {
        "accepted": True,
        "grounding_fingerprint": signing_key_fingerprint,
        "invalidated_by_revocation": False,
    }
