# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-declared-description-diverges-from-its-signed-capability-envelope-and-how-does-uns.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-declared-description-diverges-from-its-signed-capability-envelope-and-how-does-uns.warrant.json
# Markdown SHA-256:   8b4b73bdba4d6a9e5015678d0b716ed5eb1f106c737027aa2ad5f65c78515d05
# Code AST SHA-256:   35726be2cfa23b43ed31f8f8ee8ca5a57ac86347193de8c26b019892a43357ff
# Verified Classes:   SkillManifestRejected, Envelope, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field


class SkillManifestRejected(RuntimeError):
    """Raised when a tool manifest fails the signed-description + aggregate-envelope gate."""
    pass


@dataclass
class Envelope:
    scopes: list[str]
    max_distinct_paths: int | None = None
    aggregate_bounds: dict[str, int] = field(default_factory=dict)


@dataclass
class Manifest:
    tool_name: str
    description: str
    description_hash: str          # hash the registry claims to have signed
    signed_description_hash: str   # hash actually covered by the signature
    envelope: Envelope
    envelope_signature_valid: bool


# Imperative phrases that reference sibling tools are the injection signature.
CROSS_TOOL_IMPERATIVE = re.compile(
    r"\b(always|first|then|before returning|must)\b[^.]*\b"
    r"(call|invoke|pass|read|write|list|fetch)\b[^.]*\b[a-z_]+\(?",
    re.IGNORECASE,
)


def _description_covers_signature(m: Manifest) -> bool:
    actual = hashlib.sha256(m.description.encode("utf-8")).hexdigest()
    return actual == m.description_hash == m.signed_description_hash


def _has_cross_tool_imperative(m: Manifest) -> bool:
    return bool(CROSS_TOOL_IMPERATIVE.search(m.description))


def _aggregate_bounds_sufficient(m: Manifest, planned_distinct_paths: int) -> bool:
    if m.envelope.max_distinct_paths is None:
        return False  # no aggregate bound => cannot contain any multi-path sequence
    return planned_distinct_paths <= m.envelope.max_distinct_paths


def register_manifest(m: Manifest, planned_distinct_paths: int) -> Manifest:
    if not m.envelope_signature_valid:
        raise SkillManifestRejected(
            f"{m.tool_name}: envelope signature invalid; refusing registration."
        )
    if not _description_covers_signature(m):
        raise SkillManifestRejected(
            f"{m.tool_name}: description bytes are not covered by the signature; "
            f"description is an unauthenticated control channel."
        )
    if _has_cross_tool_imperative(m):
        raise SkillManifestRejected(
            f"{m.tool_name}: description contains cross-tool imperative directives; "
            f"signed text still directs behavior the envelope never contemplated."
        )
    if not _aggregate_bounds_sufficient(m, planned_distinct_paths):
        raise SkillManifestRejected(
            f"{m.tool_name}: envelope has no aggregate bound capable of containing "
            f"the {planned_distinct_paths}-path sequence its description invites."
        )
    return m
