# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-attack-surface-in-dynamically-loaded-agent-skills-manifest-to-runtime-capability-drift-as-a-load-ti.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-attack-surface-in-dynamically-loaded-agent-skills-manifest-to-runtime-capability-drift-as-a-load-ti.warrant.json
# Markdown SHA-256:   58d1c9ff43bcd8599ef5e57c4cf12d7517c25028eab71776d0be81efd4f2c4ff
# Code AST SHA-256:   51b03ba0fa5c71648b680d74523fd23d24fe5ae12f4c4d5b890a95f950b34f16
# Verified Classes:   CapabilityDriftError, Scope, DeclaredSurface, Invocation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class CapabilityDriftError(RuntimeError):
    """Raised when a skill's exercised capability surface exceeds its declared surface."""
    pass


@dataclass(frozen=True)
class Scope:
    capability: str
    path_prefix: Optional[str]  # None means unbounded -> must be rejected

    def contains(self, other: "Scope") -> bool:
        if self.capability != other.capability:
            return False
        if self.path_prefix is None:
            return True  # unbounded declared scope admits anything (and is itself invalid)
        if other.path_prefix is None:
            return False
        return other.path_prefix.startswith(self.path_prefix)


@dataclass
class DeclaredSurface:
    scopes: FrozenSet[Scope]

    def admits(self, exercised: Scope) -> bool:
        return any(d.contains(exercised) for d in self.scopes)


@dataclass
class Invocation:
    capability: str
    resolved_path: Optional[str]
    return_taint: str = "untrusted"  # default: every return is untrusted
    reads_context: bool = False


def admit_invocation(
    declared: DeclaredSurface,
    invocation: Invocation,
    agent_context_paths: FrozenSet[str],
) -> None:
    exercised = Scope(invocation.capability, invocation.resolved_path)

    # Rule 1: unbounded declaration is structurally invalid, not merely permissive.
    for d in declared.scopes:
        if d.path_prefix is None:
            raise CapabilityDriftError(
                f"manifest declares unbounded scope for {d.capability!r}; "
                f"scope drift is undetectable by construction"
            )

    # Rule 2: exercised scope must be a subset of some declared scope.
    if not declared.admits(exercised):
        raise CapabilityDriftError(
            f"scope drift: exercised {exercised} not admitted by declared {declared.scopes}"
        )

    # Rule 3: reading the agent's own context is a separate capability.
    if invocation.reads_context:
        if not any(d.capability == "context.read" for d in declared.scopes):
            raise CapabilityDriftError(
                "laundering surface: skill reads agent context without declaring context.read"
            )

    # Rule 4: return values are re-tainted at the boundary regardless of skill claim.
    if invocation.return_taint != "untrusted":
        raise CapabilityDriftError(
            f"return taint {invocation.return_taint!r} not re-tainted at boundary"
        )


def load_skill(manifest: dict, probe_invocations: list) -> DeclaredSurface:
    declared = DeclaredSurface(
        scopes=frozenset(
            Scope(c["name"], c.get("path_prefix")) for c in manifest["capabilities"]
        )
    )
    context_paths = frozenset(manifest.get("agent_context_paths", []))
    for inv in probe_invocations:
        admit_invocation(declared, inv, context_paths)
    return declared
