# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-via-dynamically-loaded-agent-tool-manifests-the-manifest-identity-vs-capability-identity-split.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-via-dynamically-loaded-agent-tool-manifests-the-manifest-identity-vs-capability-identity-split.warrant.json
# Markdown SHA-256:   f4bca6e2a9ead42d32c648d0403b7f5645a9e9f1b31cf9ed7538b82d64499a26
# Code AST SHA-256:   8c35615716f8188342603fdbca9d649a773bee14766fe3c883bc35c9e4349f6d
# Verified Classes:   CapabilityInjectionError, ResolvedCapability, SignedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityInjectionError(RuntimeError):
    """Raised when a resolved capability set is not derivable from the signed manifest."""
    pass


@dataclass(frozen=True)
class ResolvedCapability:
    verb: str
    scope: str
    arg_domain: str

    def key(self) -> str:
        return hashlib.sha256(
            json.dumps([self.verb, self.scope, self.arg_domain], sort_keys=True).encode()
        ).hexdigest()


@dataclass(frozen=True)
class SignedManifest:
    name: str
    version: str
    declared: frozenset[ResolvedCapability]
    signature: str  # verified out of band


def resolve_capabilities(
    manifest: SignedManifest,
    registry_defaults: frozenset[ResolvedCapability],
    alias_table: dict[str, ResolvedCapability],
    policy_allowlist: frozenset[ResolvedCapability],
) -> frozenset[ResolvedCapability]:
    """
    Enforce the closed-resolution invariant:
      effective = (declared, aliases-resolved) INTERSECT policy_allowlist
    Registry defaults are NEVER unioned in. Any capability reachable only via
    defaults or a name-keyed alias that dereferences outside the declared set
    is an injection and must fail closed.
    """
    # 1. Dereference aliases against content-addressed targets only.
    resolved_declared: set[ResolvedCapability] = set()
    for cap in manifest.declared:
        if cap.verb in alias_table:
            target = alias_table[cap.verb]
            # Alias must resolve to a target whose content hash is pinned;
            # a name-keyed mutable alias is rejected outright.
            if target.key() not in {c.key() for c in manifest.declared}:
                raise CapabilityInjectionError(
                    f"alias {cap.verb!r} dereferences to unpinned capability "
                    f"{target.key()}; manifest {manifest.name}@{manifest.version} "
                    f"cannot authorize it"
                )
            resolved_declared.add(target)
        else:
            resolved_declared.add(cap)

    # 2. Registry defaults are additive-only and therefore forbidden.
    smuggled = registry_defaults - resolved_declared
    if smuggled:
        raise CapabilityInjectionError(
            f"registry defaults inject {len(smuggled)} capability(ies) not declared "
            f"in signed manifest {manifest.name}@{manifest.version}: "
            f"{sorted(c.verb for c in smuggled)}"
        )

    # 3. Intersection semantics: policy may narrow, never widen.
    effective = frozenset(resolved_declared) & policy_allowlist
    if not effective and resolved_declared:
        raise CapabilityInjectionError(
            f"policy allowlist permits none of the declared capabilities for "
            f"{manifest.name}@{manifest.version}; refusing to expose tool"
        )
    return effective


def cache_key(manifest: SignedManifest, effective: frozenset[ResolvedCapability]) -> str:
    """Cache key binds BOTH manifest identity and resolved capability identity."""
    manifest_h = hashlib.sha256(
        json.dumps(
            [manifest.name, manifest.version, sorted(c.key() for c in manifest.declared)],
            sort_keys=True,
        ).encode()
    ).hexdigest()
    cap_h = hashlib.sha256(
        "".join(sorted(c.key() for c in effective)).encode()
    ).hexdigest()
    return f"{manifest_h}:{cap_h}"
