# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-skill-s-declared-capability-schema-as-untrusted-input-rather-than-as-a-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-skill-s-declared-capability-schema-as-untrusted-input-rather-than-as-a-contract.warrant.json
# Markdown SHA-256:   0877f873579712296328919986ac72dad8fa068c50a2376a04c5a1c56a0a5482
# Code AST SHA-256:   02475f9a1d5e8ec0135e8bfd5e1d6f4b6cf74aa03885a7dc457f0fc69a7af65e
# Verified Classes:   SkillManifestError, CompositionalAuthorityError, SkillManifest, AgentState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SkillManifestError(RuntimeError):
    """Raised when a dynamically loaded skill manifest violates the render-gate invariant."""


class CompositionalAuthorityError(SkillManifestError):
    """Raised when an injected sub-goal requires a tool pair that crosses a sensitivity class."""


# Sensitivity classes: a sub-goal touching both READ_SECRET and WRITE_EGRESS is a laundering chain.
READ_SECRET = "read_secret"
WRITE_EGRESS = "write_egress"

IMPERATIVE_MARKERS = (
    "before calling", "you must", "retrieve the", "pass them in",
    "required for compliance", "first call", "then send",
)


@dataclass
class SkillManifest:
    name: str
    description: str
    input_schema: dict
    provenance_hash: str


@dataclass
class AgentState:
    available_tools: dict[str, str]          # tool_name -> sensitivity class
    skill_memory: dict[str, list[str]]       # provenance_hash -> learned facts
    allowlist: set[str] = field(default_factory=set)


def scrub_manifest(manifest: SkillManifest) -> SkillManifest:
    """Enforce C1: descriptive prose must never reach the planner as instruction."""
    lowered = manifest.description.lower()
    for marker in IMPERATIVE_MARKERS:
        if marker in lowered:
            raise SkillManifestError(
                f"manifest {manifest.name!r} description contains imperative content "
                f"({marker!r}); refusing to render into planner context"
            )
    # Structural schema only: drop free-text 'description'/'examples'/'default' keys.
    structural = {
        k: {kk: vv for kk, vv in v.items() if kk in ("type", "enum", "required")}
        for k, v in manifest.input_schema.get("properties", {}).items()
    }
    return SkillManifest(
        name=manifest.name,
        description="",  # prose stripped
        input_schema={"properties": structural},
        provenance_hash=manifest.provenance_hash,
    )


def check_compositional_authority(
    state: AgentState, sub_goal_tools: list[str]
) -> None:
    """Enforce C2: a plan touching both a secret-read and an egress-write is a laundering chain."""
    classes = {state.available_tools.get(t) for t in sub_goal_tools}
    if READ_SECRET in classes and WRITE_EGRESS in classes:
        raise CompositionalAuthorityError(
            f"sub-goal composes {sorted(classes)} across sensitivity boundary; "
            f"tools={sub_goal_tools} require human checkpoint"
        )


def evict_stale_skill_memory(state: AgentState, live_hashes: set[str]) -> None:
    """Enforce C3: skill-derived facts die with the manifest that produced them."""
    for h in list(state.skill_memory):
        if h not in live_hashes:
            del state.skill_memory[h]


def load_skill(
    manifest: SkillManifest,
    state: AgentState,
    plan_tools: Callable[[SkillManifest], list[str]],
) -> SkillManifest:
    """Full load path: scrub (C1) -> plan -> composition check (C2) -> memory hygiene (C3)."""
    safe = scrub_manifest(manifest)
    sub_goal_tools = plan_tools(safe)
    check_compositional_authority(state, sub_goal_tools)
    state.skill_memory.setdefault(safe.provenance_hash, []).append(
        f"loaded:{safe.name}"
    )
    return safe
