# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-a-delegated-consent-token-after-a-scope-narrowing-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-a-delegated-consent-token-after-a-scope-narrowing-hop.warrant.json
# Markdown SHA-256:   0c88bfa055daf14086ebe28ca31de728fe6eb56b16cb62f80bd08741ddaecfa7
# Code AST SHA-256:   ea657195e7b74ed30a0b55f628464638951dc6d759c71cd94885e00fbdbca896
# Verified Classes:   AttestationContextMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AttestationContextMismatch(RuntimeError):
    """Raised when a delegated token's attestation does not describe the presenting context."""
    pass


def verify_delegated_token(token, runtime_ctx_id, parent_scope):
    # 1. Signature chain integrity (assumed pre-checked by caller).
    if not token.signature_valid:
        raise AttestationContextMismatch("signature chain broken")

    # 2. Scope monotonicity: child scope must be a subset of parent scope.
    if not token.scope.issubset(parent_scope):
        raise AttestationContextMismatch(
            f"scope {token.scope} not subset of parent {parent_scope}"
        )

    # 3. Attestation binding: the attestation must describe the PRESENTING context.
    #    This is the conjunct most verifiers omit. A narrowing hop across an
    #    instance boundary copies a stale attestation; it verifies but lies.
    attested_ctx = token.attestation.context_id
    if token.attestation.inherit_marker:
        # Only legal when the child provably shares the parent's context.
        if not runtime_ctx_id.shares_namespace_with(attested_ctx):
            raise AttestationContextMismatch(
                f"inherit marker set but ctx {runtime_ctx_id} does not share "
                f"namespace with attested ctx {attested_ctx}"
            )
    elif attested_ctx != runtime_ctx_id:
        raise AttestationContextMismatch(
            f"attestation bound to ctx {attested_ctx} but presented by "
            f"ctx {runtime_ctx_id}; re-attestation required after narrowing hop"
        )

    return True
