# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-signed-skill-manifest-whose-signature-validates-but-whose-declared-capability-set-is-a-superset-of-wha.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-signed-skill-manifest-whose-signature-validates-but-whose-declared-capability-set-is-a-superset-of-wha.warrant.json
# Markdown SHA-256:   256a12b1baf7c84997c5add7552c03463b9d49037f373673883538cdcf8fa0a2
# Code AST SHA-256:   431db34c953052d46def61c202dcfac6f94c8fcaaf0cbe1f27aa660f19529839
# Verified Classes:   CapabilityScopeViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class CapabilityScopeViolation(RuntimeError):
    """Raised when a manifest's declared capabilities exceed the signer's grant scope."""
    pass


def load_manifest(manifest, signature, trust_store, policy_store):
    # 1. Verify signature over the exact canonical bytes.
    signer_id = trust_store.verify(manifest.canonical_bytes(), signature)
    if signer_id is None:
        raise CapabilityScopeViolation(f"signature did not validate for key {signature.key_id}")

    # 2. Parse only after verification, from the same bytes.
    parsed = parse_manifest(manifest.canonical_bytes())
    if parsed.capability_set() != manifest.declared_capabilities():
        raise CapabilityScopeViolation("parsed capabilities diverge from signed body")

    # 3. Monotonic attenuation along the delegation chain.
    chain = trust_store.delegation_chain(signer_id)
    for parent, child in zip(chain, chain[1:]):
        if not policy_store.scope_subset(policy_store.grant_scope(child),
                                         policy_store.grant_scope(parent)):
            raise CapabilityScopeViolation(
                f"delegation widens scope: {child} exceeds {parent}")

    # 4. Effective grant from policy store, never from the manifest.
    effective_grant = policy_store.grant_scope(signer_id)
    if effective_grant is None:
        raise CapabilityScopeViolation(f"no grant scope on record for signer {signer_id}")

    # 5. Reject supersets; wildcards require explicit authorization.
    declared = parsed.capability_set()
    if "*" in declared and not policy_store.may_issue_wildcard(signer_id):
        raise CapabilityScopeViolation(f"signer {signer_id} may not issue wildcard capabilities")
    if not policy_store.scope_subset(declared, effective_grant):
        excess = declared - effective_grant
        raise CapabilityScopeViolation(
            f"manifest declares {sorted(excess)} beyond grant scope of {signer_id}")

    # 6. Enforce the intersection, not the declaration.
    parsed.set_enforced_capabilities(declared & effective_grant)
    return parsed
