# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-tool-registry-skill-injection-that-survives-schema-revalidation-due-to-descriptor-level-prompt-smuggling.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-tool-registry-skill-injection-that-survives-schema-revalidation-due-to-descriptor-level-prompt-smuggling.warrant.json
# Markdown SHA-256:   ef21f09d2779aca64cf109e9d0dca8e2ec282432efffcc7ad71859cf8ec92701
# Code AST SHA-256:   3a467ea415388a0ee7bcc0732e81dd3255e6c0ca4fbf97edb77ca9ca1ae7a31f
# Verified Classes:   DescriptorTrustViolation, Descriptor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Iterable


class DescriptorTrustViolation(RuntimeError):
    """Raised when a descriptor set violates descriptor-locality or cache-hash invariants."""


@dataclass(frozen=True)
class Descriptor:
    name: str
    signer: str
    description: str
    schema: dict


def descriptor_hash(descs: Iterable[Descriptor]) -> str:
    h = hashlib.sha256()
    for d in sorted(descs, key=lambda x: x.name):
        h.update(d.name.encode())
        h.update(d.signer.encode())
        h.update(d.description.encode())
        h.update(json.dumps(d.schema, sort_keys=True).encode())
    return h.hexdigest()


def admit_descriptor_set(descs: list[Descriptor], checkpoint_manifest_hash: str | None) -> str:
    names = {d.name for d in descs}

    # Invariant 1: descriptor locality — no cross-signer sibling reference.
    for d in descs:
        for other in names - {d.name}:
            if other in d.description:
                sibling = next(x for x in descs if x.name == other)
                if sibling.signer != d.signer:
                    raise DescriptorTrustViolation(
                        f"descriptor '{d.name}' (signer={d.signer}) references "
                        f"sibling '{other}' (signer={sibling.signer}) across trust boundary"
                    )

    current = descriptor_hash(descs)

    # Invariant 2: resume must fail closed on descriptor-set mutation.
    if checkpoint_manifest_hash is not None and current != checkpoint_manifest_hash:
        raise DescriptorTrustViolation(
            f"descriptor-set hash {current[:12]} != checkpoint {checkpoint_manifest_hash[:12]}; "
            "tool surface mutated under resumed agent"
        )

    return current


def resume_task(descs: list[Descriptor], checkpoint_manifest_hash: str) -> str:
    try:
        return admit_descriptor_set(descs, checkpoint_manifest_hash)
    except DescriptorTrustViolation as e:
        # Fail closed: do not continue with a silently mutated preamble.
        raise DescriptorTrustViolation(f"resume aborted: {e}") from e
