# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-skill-s-declared-capability-schema-as-the-security-boundary-rather-than-its-description-text-and-what-b.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-skill-s-declared-capability-schema-as-the-security-boundary-rather-than-its-description-text-and-what-b.warrant.json
# Markdown SHA-256:   f907c13dc6ff07a8586a95891dc0056dbc4baff3980a04bc32478f17dc2e7c43
# Code AST SHA-256:   dc671cc509771d75f51b81089af32230f83548710288f61fc36dd600ae902425
# Verified Classes:   SkillScopeViolation, OpenSchemaEscape
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SkillScopeViolation(RuntimeError):
    """Raised when a bound skill invocation requests capability beyond policy."""
    pass


class OpenSchemaEscape(SkillScopeViolation):
    """Raised at admission when a schema contains fields that can absorb
    dropped arguments and bypass bind-time scope checks."""
    pass


OPEN_FIELD_NAMES = {"notes", "metadata", "extra", "misc", "context_blob"}


def admit_skill(schema: dict) -> None:
    """Admission gate: reject open schemas before they enter selection pool."""
    for field_name, spec in schema.get("properties", {}).items():
        if field_name in OPEN_FIELD_NAMES:
            raise OpenSchemaEscape(
                f"skill '{schema.get('name')}' declares open field "
                f"'{field_name}'; arguments can be re-homed past bind checks"
            )
        if spec.get("type") == "object" and spec.get("additionalProperties"):
            raise OpenSchemaEscape(
                f"skill '{schema.get('name')}' field '{field_name}' allows "
                f"additionalProperties; not a closed boundary"
            )


def bind_and_enforce(schema: dict, arguments: dict, policy_scopes: set[str]) -> set[str]:
    """Bind gate: derive scopes from actual arguments, reject on excess."""
    admit_skill(schema)

    granted: set[str] = set()
    for field_name, value in arguments.items():
        spec = schema["properties"].get(field_name)
        if spec is None:
            raise SkillScopeViolation(
                f"argument '{field_name}' not in schema for "
                f"'{schema.get('name')}'"
            )
        field_scope = spec.get("x-scope")
        if field_scope:
            granted.add(field_scope)

    excess = granted - policy_scopes
    if excess:
        # Description text is deliberately NOT consulted here.
        raise SkillScopeViolation(
            f"skill '{schema.get('name')}' requires scopes {sorted(excess)} "
            f"not granted by policy {sorted(policy_scopes)}; "
            f"description claims are non-authoritative"
        )
    return granted
