# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-dynamically-loaded-skill-s-declared-capability-manifest-and-how-does-the-manifest-signature-behavior.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-dynamically-loaded-skill-s-declared-capability-manifest-and-how-does-the-manifest-signature-behavior.warrant.json
# Markdown SHA-256:   1a0fd5e71e59584103d3d8d7a4d40f6ca85eb81dd39d3267b0244ca896c62272
# Code AST SHA-256:   e1b502c6ef99b6517a43e13919aef61dc75a886d3fa7a56087a0205ae9cbf62a
# Verified Classes:   ManifestBodyDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ManifestBodyDivergenceError(RuntimeError):
    """Raised when a skill's executed behavior exceeds its signed manifest's declared capabilities."""
    pass


def authorize_skill_invocation(manifest, body_digest, default_envelope):
    # Invariant: a signature over a manifest that does not bind the body
    # authorizes nothing about the body. Narrow, never widen.
    if manifest.signature_covers_body_digest:
        if body_digest != manifest.body_digest:
            raise ManifestBodyDivergenceError(
                f"body digest {body_digest} does not match signed manifest "
                f"{manifest.body_digest} for skill {manifest.skill_id}"
            )
        envelope = manifest.capabilities
    else:
        # Manifest-only signature: treat declaration as a hint, enforce intersection.
        envelope = intersect(manifest.capabilities, default_envelope)

    # Return channel is a capability; read_only must not imply inert output.
    if "read_only" in manifest.side_effect_class and "return:unrestricted" not in envelope:
        envelope = envelope | {"return:inspected"}

    # First invocation is always quarantined regardless of declaration.
    envelope = envelope | {"first_run:quarantine"}

    return envelope


def invoke_skill(skill, ctx, envelope):
    if "first_run:quarantine" in envelope and skill.invocation_count == 0:
        result = skill.callable(ctx, egress=False, credential_reads=False)
        if violates_capability_class(result, skill.manifest.side_effect_class):
            raise ManifestBodyDivergenceError(
                f"skill {skill.manifest.skill_id} returned content inconsistent "
                f"with declared side_effect_class {skill.manifest.side_effect_class!r} "
                f"on first invocation; quarantined"
            )
        return result
    return skill.callable(ctx)
