# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-dynamically-loaded-skill-manifest-whose-declared-capability-set-is-a-strict-superset-of-the-manifest-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-dynamically-loaded-skill-manifest-whose-declared-capability-set-is-a-strict-superset-of-the-manifest-i.warrant.json
# Markdown SHA-256:   d342ccc216875757a8fd57ab5759f0a4921140a49bc12fee8748028b11fa131a
# Code AST SHA-256:   ba26e82f2d6ecb75f40c49cbe07ec06f552118cfdd93aa4c8bd05093a0fd35a1
# Verified Classes:   CapabilitySupersetError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilitySupersetError(RuntimeError):
    """Raised when an executed skill manifest grants capabilities
    beyond what its signed envelope authorized."""
    pass


def build_execution_manifest(signed_envelope: dict, overlay: dict | None = None) -> dict:
    """
    Compose the signed envelope with an optional overlay, then re-derive
    the capability digest over the composed set. The caller MUST verify
    the returned digest against the signed envelope's digest before
    admitting the manifest to the execution layer.
    """
    composed = {
        "tools": dict(signed_envelope["tools"]),
        "scope": dict(signed_envelope.get("scope", {})),
        "sig": signed_envelope["sig"],
        "signed_digest": signed_envelope["capability_digest"],
    }
    if overlay:
        for tool, scope in overlay.get("tools", {}).items():
            if tool not in composed["tools"]:
                # Overlay introduces a tool the signer never authorized.
                raise CapabilitySupersetError(
                    f"overlay adds unauthorized tool {tool!r}"
                )
            # Overlay may only narrow scope, never widen it.
            signed_scope = composed["scope"].get(tool, "/")
            if not _is_subpath(scope, signed_scope):
                raise CapabilitySupersetError(
                    f"overlay widens scope for {tool!r}: "
                    f"{scope!r} not within signed {signed_scope!r}"
                )
            composed["scope"][tool] = scope
    composed["capability_digest"] = _digest(composed["tools"], composed["scope"])
    return composed


def admit_manifest(execution_manifest: dict, tool_registry) -> None:
    """
    Final gate before the manifest is exposed to the reasoning loop.
    Rejects if the composed digest diverges from the signed digest, or
    if any tool resolves to an implementation broader than signed.
    """
    if execution_manifest["capability_digest"] != execution_manifest["signed_digest"]:
        raise CapabilitySupersetError(
            "composed capability digest diverges from signed digest"
        )
    for tool, scope in execution_manifest["scope"].items():
        impl = tool_registry.resolve(tool)
        if impl is None:
            raise CapabilitySupersetError(f"unresolvable tool {tool!r}")
        if not _is_subpath(impl.declared_scope, scope):
            raise CapabilitySupersetError(
                f"tool {tool!r} resolves to implementation with scope "
                f"{impl.declared_scope!r} exceeding signed {scope!r}"
            )


def _is_subpath(candidate: str, parent: str) -> bool:
    return candidate == parent or candidate.startswith(parent.rstrip("/") + "/")


def _digest(tools: dict, scope: dict) -> str:
    import hashlib, json
    canonical = json.dumps(
        {"tools": sorted(tools), "scope": {k: scope[k] for k in sorted(scope)}},
        separators=(",", ":"),
    )
    return hashlib.sha256(canonical.encode()).hexdigest()
