# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-skill-manifest-capability-descriptor-laundering-across-dynamic-skill-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-skill-manifest-capability-descriptor-laundering-across-dynamic-skill-reload.warrant.json
# Markdown SHA-256:   d755f7fcc6ea69c52b73e74a42f359a58b85083988195f68bd8430e82b0d15bd
# Code AST SHA-256:   b49e0c8db6c16e6dabc4d8a80048cbbf193d24d15c904c5267231312cd202c7b
# Verified Classes:   ManifestDivergenceError, SkillArtifact, CachedTrust
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestDivergenceError(RuntimeError):
    """Raised when a skill's declared descriptor and its actual authority disagree."""
    pass


@dataclass
class SkillArtifact:
    name: str
    descriptor_bytes: bytes
    implementation_bytes: bytes
    declared_scope: frozenset          # e.g. {"fs:read:/data"}
    enforced_envelope: frozenset       # derived from sandbox, NOT from manifest

    @property
    def artifact_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.descriptor_bytes)
        h.update(self.implementation_bytes)
        return h.hexdigest()

    @property
    def descriptor_hash(self) -> str:
        return hashlib.sha256(self.descriptor_bytes).hexdigest()


@dataclass
class CachedTrust:
    """A planner belief like 'auto-invoke, no confirmation' bound to an artifact."""
    artifact_hash: str
    descriptor_hash: str
    envelope: frozenset
    auto_invoke: bool = True


def reload_skill(prev: SkillArtifact, new: SkillArtifact,
                 trust: CachedTrust) -> CachedTrust:
    # 1. Descriptor/implementation divergence is the high-signal anomaly.
    if new.artifact_hash != prev.artifact_hash and \
       new.descriptor_hash == prev.descriptor_hash:
        raise ManifestDivergenceError(
            f"skill {new.name!r}: implementation changed while descriptor "
            f"stayed byte-identical; refusing to carry forward trust"
        )

    # 2. Sandbox must not grant authority the manifest never declared.
    over_grant = new.enforced_envelope - new.declared_scope
    if over_grant:
        raise ManifestDivergenceError(
            f"skill {new.name!r}: sandbox grants {sorted(over_grant)} "
            f"not declared in manifest; descriptor is not a valid authority claim"
        )

    # 3. Cached planner policy is only valid against the exact artifact it
    #    was formed on, and only if the envelope is unchanged.
    if new.artifact_hash == trust.artifact_hash and \
       new.enforced_envelope == trust.envelope:
        return trust

    # Divergence or envelope drift: invalidate and force re-approval.
    return CachedTrust(
        artifact_hash=new.artifact_hash,
        descriptor_hash=new.descriptor_hash,
        envelope=new.enforced_envelope,
        auto_invoke=False,
    )
