# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-signed-skill-manifest-pass-verification-yet-still-execute-with-capabilities-it-never-attested.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-signed-skill-manifest-pass-verification-yet-still-execute-with-capabilities-it-never-attested.warrant.json
# Markdown SHA-256:   3bf6a46e16463bfd8977b30cc421fdc6a3d63decddae54f9de8d721465ef106c
# Code AST SHA-256:   f3e5e7d368105635ff783c224339d876869781d9f0b2e2d36fb0a4924a638426
# Verified Classes:   CapabilityAttestationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilityAttestationError(RuntimeError):
    """Raised when effective runtime authority exceeds the attested capability set."""
    pass


def verify_and_instantiate(manifest, runtime, policy_snapshot):
    # 1. Byte-level provenance: signature and hash over the signed bundle.
    if not manifest.verify_signature():
        raise CapabilityAttestationError("manifest signature invalid")
    if not manifest.verify_bundle_hash():
        raise CapabilityAttestationError("bundle hash mismatch")

    # 2. Attested set = declared ∩ policy-allowed, computed by the verifier,
    #    never by the executor. Exact matching only.
    declared = frozenset(manifest.capabilities)
    allowed = frozenset(policy_snapshot.allowed_capabilities)
    attested = declared & allowed

    # 3. Materialize the sandbox pinned to the policy snapshot, then enumerate
    #    the authority the worker actually holds. Refuse on unenumerable.
    worker = runtime.instantiate(manifest.bundle, policy_snapshot=policy_snapshot)
    effective = worker.enumerate_effective_capabilities()
    if effective is None:
        raise CapabilityAttestationError(
            "effective capability set is unenumerable; cannot prove subset of attested"
        )
    effective = frozenset(effective)

    # 4. The invariant that the signature alone never guaranteed.
    overreach = effective - attested
    if overreach:
        raise CapabilityAttestationError(
            f"effective authority exceeds attested set: {sorted(overreach)}"
        )

    # 5. Eager re-check: no lazy widening between verify and first instruction.
    if worker.policy_generation() != policy_snapshot.generation:
        raise CapabilityAttestationError(
            "policy changed between verification and instantiation"
        )

    return worker
