# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-plugin-manifest-s-declared-capabilities-over-its-observed-tool-call-behavior-the-skill-injection-surface-in-dyn.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-plugin-manifest-s-declared-capabilities-over-its-observed-tool-call-behavior-the-skill-injection-surface-in-dyn.warrant.json
# Markdown SHA-256:   3a87f972128a9bb231270def751cebf975a33789228e2d956f209b16be8b94c1
# Code AST SHA-256:   3d6c509bd06f3bc2525f0476262ac3dba5740568c95c875659634050c68e930c
# Verified Classes:   SkillInjectionError, Regime, Manifest, ObservedEffects, ToolRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SkillInjectionError(RuntimeError):
    """Raised when a tool's observed behavior contradicts its manifest claims
    and the runtime was about to authorize it under the trusted regime."""


class Regime(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


@dataclass
class Manifest:
    name: str
    declared_fs_scope: str          # "none" | "read" | "write"
    declared_network: bool
    trust_tier: str                 # attacker-controlled string; NOT evidence
    publisher_key: Optional[str]    # must match a loader-side allowlist


@dataclass
class ObservedEffects:
    fs_writes: int = 0
    fs_reads: int = 0
    sockets_opened: int = 0
    subprocesses: int = 0


@dataclass
class ToolRecord:
    manifest: Manifest
    implementation_hash: str
    effects: ObservedEffects = field(default_factory=ObservedEffects)


LOADER_TRUSTED_KEYS = {"publisher-a", "publisher-b"}  # loader-side, not manifest-side


def classify_regime(rec: ToolRecord, pinned_hash: Optional[str]) -> Regime:
    """Provenance binding decides the regime. trust_tier is deliberately ignored:
    it lives in the manifest and cannot bootstrap its own trust."""
    if rec.manifest.publisher_key not in LOADER_TRUSTED_KEYS:
        return Regime.UNTRUSTED
    if pinned_hash is None or pinned_hash != rec.implementation_hash:
        return Regime.UNTRUSTED
    return Regime.TRUSTED


def authorize_invocation(rec: ToolRecord, pinned_hash: Optional[str]) -> Regime:
    regime = classify_regime(rec, pinned_hash)
    if regime is Regime.UNTRUSTED:
        # Advisory-only: sandbox to the empty intersection, no privileged context.
        return regime

    # Trusted regime still requires post-call reconciliation. We check the
    # *prior* observed effects before granting the next call, because a single
    # divergence poisons every episode built on it.
    m = rec.manifest
    e = rec.effects
    if m.declared_fs_scope == "none" and e.fs_writes > 0:
        raise SkillInjectionError(
            f"tool {m.name!r} declared fs_scope=none but performed "
            f"{e.fs_writes} write(s); manifest/implementation provenance "
            f"diverged, quarantining and invalidating dependent episodes"
        )
    if not m.declared_network and e.sockets_opened > 0:
        raise SkillInjectionError(
            f"tool {m.name!r} declared network=false but opened "
            f"{e.sockets_opened} socket(s)"
        )
    if m.declared_fs_scope == "read" and e.fs_writes > 0:
        raise SkillInjectionError(
            f"tool {m.name!r} declared fs_scope=read but wrote {e.fs_writes} time(s)"
        )
    return regime


def load_and_gate(rec: ToolRecord, pinned_hash: Optional[str]) -> Regime:
    """Entry point: any divergence is fatal, not advisory."""
    return authorize_invocation(rec, pinned_hash)


if __name__ == "__main__":
    lying = ToolRecord(
        manifest=Manifest(
            name="summarize_doc",
            declared_fs_scope="none",
            declared_network=False,
            trust_tier="verified",          # ignored
            publisher_key="publisher-a",
        ),
        implementation_hash=hashlib.sha256(b"handler").hexdigest(),
        effects=ObservedEffects(fs_writes=1),
    )
    try:
        load_and_gate(lying, pinned_hash=lying.implementation_hash)
    except SkillInjectionError as exc:
        print(f"blocked: {exc}")
