# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-tool-manifest-whose-declared-capability-set-is-a-strict-superset-of-the-capability-set-observed-at-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-tool-manifest-whose-declared-capability-set-is-a-strict-superset-of-the-capability-set-observed-at-first-invocation.warrant.json
# Markdown SHA-256:   6f6afc5bf77f24b0572637a5b84f70c072e215fb6c1d41a079ab552d49ae8d79
# Code AST SHA-256:   da628b633ee1571563de7e005e9c731432b6a677c27083ee5b54ade0a53d1fda
# Verified Classes:   ManifestCapabilityDriftError, LoadedPlugin
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ManifestCapabilityDriftError(RuntimeError):
    """Raised when a dynamically loaded manifest declares privileged
    capabilities that were not observed at first invocation, indicating
    a potential skill-injection staging surface."""
    pass


PRIVILEGED = frozenset({"proc.spawn", "net.egress", "fs.write",
                        "db.write", "proc.delete", "auth.escalate"})


@dataclass
class LoadedPlugin:
    name: str
    declared: frozenset
    observed: frozenset = field(default_factory=frozenset)
    first_invocation_done: bool = False


def finalize_first_invocation(plugin: LoadedPlugin) -> frozenset:
    """Called once after the first invocation completes. Returns the
    effective grant. Raises if privileged declared-but-unobserved caps
    exist, because the observation cache must not silently become the
    de facto grant."""
    if plugin.first_invocation_done:
        raise ManifestCapabilityDriftError(
            f"{plugin.name}: finalize called twice; cache already hardened"
        )
    dormant = plugin.declared - plugin.observed
    privileged_dormant = dormant & PRIVILEGED
    if privileged_dormant:
        raise ManifestCapabilityDriftError(
            f"{plugin.name}: declared-but-unobserved privileged caps "
            f"{sorted(privileged_dormant)}; refusing to cache observed set "
            f"{sorted(plugin.observed)} as effective grant"
        )
    plugin.first_invocation_done = True
    return plugin.declared  # grant the declared set, not the observed set


# Example: a plugin that over-declares and stages behavior.
p = LoadedPlugin(
    name="ingest-helper",
    declared=frozenset({"fs.read", "proc.spawn", "net.egress"}),
    observed=frozenset({"fs.read"}),
)
try:
    finalize_first_invocation(p)
except ManifestCapabilityDriftError as e:
    print(f"REJECTED: {e}")
