# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-skill-manifest-that-re-signs-cleanly-while-mutating-its-tool-descriptor-s-behavioral-surface-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-skill-manifest-that-re-signs-cleanly-while-mutating-its-tool-descriptor-s-behavioral-surface-mid-session.warrant.json
# Markdown SHA-256:   d0a46590c69714bb08c47c5ed5871713ae22bcde968b22f140bc798f62d2fe97
# Code AST SHA-256:   1fb7a5429dec9a0f9f90bcad1a6b06657307562b2ba9957db2b1a45f50625e2b
# Verified Classes:   DescriptorDriftError, CapabilityGrant, ToolDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DescriptorDriftError(RuntimeError):
    """Raised when the executing tool descriptor diverges from the granted artifact."""


@dataclass(frozen=True)
class CapabilityGrant:
    skill_id: str
    descriptor_hash: str
    capabilities: frozenset[str]
    side_effect_class: str


@dataclass
class ToolDescriptor:
    name: str
    side_effect_class: str
    capabilities: set[str]
    params: dict[str, str] = field(default_factory=dict)

    def content_hash(self) -> str:
        # Canonical serialization: order-independent, includes params and side-effect class.
        payload = "|".join([
            self.name,
            self.side_effect_class,
            ",".join(sorted(self.capabilities)),
            ",".join(f"{k}:{v}" for k, v in sorted(self.params.items())),
        ])
        return hashlib.sha256(payload.encode()).hexdigest()


# Parameters whose presence gates a side effect; their addition is a behavioral change.
SIDE_EFFECT_GATING_PARAMS = {"follow_redirects", "post_body", "output_path", "callback_url"}


def admit_or_refresh(
    grant: CapabilityGrant,
    live_descriptor: ToolDescriptor,
    signature_valid: bool,
) -> CapabilityGrant:
    if not signature_valid:
        raise DescriptorDriftError(
            f"signature invalid for {grant.skill_id}; refusing admission"
        )

    live_hash = live_descriptor.content_hash()

    # Content-hash binding: identity match is NOT sufficient.
    if live_hash != grant.descriptor_hash:
        # Re-hydration path: diff against the granted artifact, not against skill_id.
        added_caps = live_descriptor.capabilities - grant.capabilities
        added_gating_params = SIDE_EFFECT_GATING_PARAMS & (
            set(live_descriptor.params) - set()
        )
        class_changed = live_descriptor.side_effect_class != grant.side_effect_class

        if added_caps or class_changed:
            raise DescriptorDriftError(
                f"descriptor drift for {grant.skill_id}: "
                f"added_caps={sorted(added_caps)} class_changed={class_changed} "
                f"granted_hash={grant.descriptor_hash[:12]} live_hash={live_hash[:12]}"
            )

        # Capability narrowing or param-only change: re-issue grant on new hash.
        return CapabilityGrant(
            skill_id=grant.skill_id,
            descriptor_hash=live_hash,
            capabilities=frozenset(live_descriptor.capabilities),
            side_effect_class=live_descriptor.side_effect_class,
        )

    return grant


def enforce_least_privilege(
    grant: CapabilityGrant, descriptor: ToolDescriptor, requested_cap: str
) -> None:
    # Field-level scope: the concrete token must be in the grant, not merely its class.
    if grant.descriptor_hash != descriptor.content_hash():
        raise DescriptorDriftError(
            f"executing descriptor hash {descriptor.content_hash()[:12]} "
            f"does not match grant {grant.descriptor_hash[:12]}"
        )
    if requested_cap not in grant.capabilities:
        raise DescriptorDriftError(
            f"capability {requested_cap!r} not granted for {grant.skill_id}; "
            f"granted={sorted(grant.capabilities)}"
        )
