# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-capability-from-diverging-from-runtime-observed-capability-in-dynamically-loaded-agent-skills.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-capability-from-diverging-from-runtime-observed-capability-in-dynamically-loaded-agent-skills.warrant.json
# Markdown SHA-256:   5c26eb61739ba8e0552a4da18d9cd2b7eadb03614dcb91a5c11f7ac9695c52b3
# Code AST SHA-256:   f1f69d5ff0461033d7469c99568d06b8d7d5105ed8a3d524c91caf5c3ced8e6d
# Verified Classes:   CapabilityScopeViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityScopeViolation(RuntimeError):
    """Raised when a skill's declared or enforced capability set exceeds
    what its description entails (violates R ⊆ D ⊆ I)."""


def validate_skill_load(
    declared: set[str],
    enforced: set[str],
    description_implied: set[str],
    skill_name: str,
) -> None:
    # R ⊆ D : sandbox must not grant more than the manifest declares.
    over_grant = enforced - declared
    if over_grant:
        raise CapabilityScopeViolation(
            f"skill {skill_name!r}: sandbox grants {sorted(over_grant)} "
            f"not declared in manifest; refusing to load"
        )

    # D ⊆ I : manifest must not declare more than the description entails.
    over_declare = declared - description_implied
    if over_declare:
        raise CapabilityScopeViolation(
            f"skill {skill_name!r}: manifest declares {sorted(over_declare)} "
            f"not entailed by description; this is the skill-injection slack. "
            f"Refusing to load (narrow the permission or reject)."
        )

    # Argument-domain check: a parameter that admits values outside the
    # permission domain (e.g. unbounded path under fs:read) must be
    # constrained or the load is rejected.
    if "fs:read" in declared and not _has_path_predicate(declared):
        raise CapabilityScopeViolation(
            f"skill {skill_name!r}: fs:read declared without a path-predicate "
            f"constraint; argument domain is unbounded relative to permission"
        )


def _has_path_predicate(declared: set[str]) -> bool:
    # A real implementation inspects the schema for a prefix/regex constraint
    # on path-like parameters. Placeholder: require an explicit predicate tag.
    return any(cap.startswith("fs:read:") for cap in declared)
