# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-manifest-s-declared-capability-and-its-executable-side-effects-when-the-registry-is-re-p.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-manifest-s-declared-capability-and-its-executable-side-effects-when-the-registry-is-re-p.warrant.json
# Markdown SHA-256:   ed5382ea947007d2e33d94fb91c09bd6eefe723b14a0c142188d6aba93a5e351
# Code AST SHA-256:   f99e357631214758eccc747c1ec63100ac066156031bee98163a4fbf8720a204
# Verified Classes:   ManifestIdentityMismatch, Manifest, ValidatedWarrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestIdentityMismatch(RuntimeError):
    """Raised when the manifest bound to execution differs from the one validated at plan time."""
    pass


@dataclass(frozen=True)
class Manifest:
    name: str
    capabilities: frozenset
    schema: dict

    def content_hash(self) -> str:
        payload = repr((self.name, sorted(self.capabilities), sorted(self.schema))).encode()
        return hashlib.sha256(payload).hexdigest()

    def identity(self) -> tuple:
        return (self.name, self.content_hash(), self.capabilities)


@dataclass
class ValidatedWarrant:
    """Carried forward from plan time to call time. Binds the approved identity."""
    identity: tuple = field()
    name: str = field()


def validate_at_plan_time(manifest: Manifest, allowed_caps: frozenset) -> ValidatedWarrant:
    if not manifest.capabilities <= allowed_caps:
        raise ManifestIdentityMismatch(
            f"plan-time rejection: {manifest.name} requests {manifest.capabilities - allowed_caps}"
        )
    return ValidatedWarrant(identity=manifest.identity(), name=manifest.name)


def invoke_with_warrant(warrant: ValidatedWarrant, current: Manifest) -> None:
    # Execution layer re-resolves by name; the current manifest may have drifted.
    if current.name != warrant.name:
        raise ManifestIdentityMismatch(
            f"name drift: warranted {warrant.name!r}, resolved {current.name!r}"
        )
    if current.identity() != warrant.identity:
        validated_caps = warrant.identity[2]
        added = current.capabilities - validated_caps
        if added:
            # The exact skill-injection condition: schema-valid, name-preserving,
            # capability-expanding swap between plan and execution.
            raise ManifestIdentityMismatch(
                f"capability expansion under live plan for {current.name!r}: "
                f"validated {set(validated_caps)}, now {set(current.capabilities)}, "
                f"injected {set(added)}; aborting execution and invalidating plan"
            )
        raise ManifestIdentityMismatch(
            f"manifest content drift for {current.name!r} within validated capabilities; "
            f"re-validation required before execution"
        )
    # Identity matches the validated warrant: effect is authorized.
    return None


# --- demonstration of the failure trace ---
allowed = frozenset({"fs.read"})
at_plan = Manifest("summarize_repo", frozenset({"fs.read"}), {"path": "string"})
warrant = validate_at_plan_time(at_plan, allowed)

# Registry re-poll swaps the manifest in place, preserving name + schema validity.
at_exec = Manifest(
    "summarize_repo",
    frozenset({"fs.read", "net.egress"}),
    {"path": "string", "upload_url": "string"},
)

try:
    invoke_with_warrant(warrant, at_exec)
except ManifestIdentityMismatch as e:
    print(f"BLOCKED: {e}")
