# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-has-crossed-from-behavioral-drift-into-capability-expansion.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-has-crossed-from-behavioral-drift-into-capability-expansion.warrant.json
# Markdown SHA-256:   31dd81c664ed06855821eb80d46416406cfadcded0bf0b273a6987179e29da73
# Code AST SHA-256:   8d6abadc223bca41e21a52cbd32f4abb8676fe4446939b7d72a63be42b284225
# Verified Classes:   CapabilityExpansionError, ToolSpec, CapabilitySnapshot
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Callable


class CapabilityExpansionError(RuntimeError):
    """Raised when a runtime skill mutation expands the effective capability set."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    schema: dict
    side_effect: str  # "read" | "write_scoped" | "write_unscoped" | "network" | "exec"

    def fingerprint(self) -> str:
        canon = json.dumps(
            {"name": self.name, "schema": self.schema, "side_effect": self.side_effect},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canon.encode()).hexdigest()


@dataclass
class CapabilitySnapshot:
    tools: dict[str, ToolSpec] = field(default_factory=dict)
    # composition edges: tool -> tools whose OUTPUT feeds this tool's INPUT
    edges: dict[str, set[str]] = field(default_factory=dict)

    def reachable_side_effects(self, root: str) -> set[str]:
        seen, stack, effects = set(), [root], set()
        while stack:
            cur = stack.pop()
            if cur in seen or cur not in self.tools:
                continue
            seen.add(cur)
            effects.add(self.tools[cur].side_effect)
            stack.extend(self.edges.get(cur, set()))
        return effects


def detect_capability_delta(
    prior: CapabilitySnapshot,
    current: CapabilitySnapshot,
    entry_tool: str,
) -> list[str]:
    """Return structural delta reasons. Empty list == no expansion."""
    reasons: list[str] = []

    for name, spec in current.tools.items():
        if name not in prior.tools:
            reasons.append(f"new_tool:{name}")
        elif prior.tools[name].fingerprint() != spec.fingerprint():
            reasons.append(f"schema_mutation:{name}")

    for name in prior.tools:
        if name not in current.tools:
            reasons.append(f"tool_removed:{name}")

    # Composition reachability: the non-obvious check.
    prior_effects = prior.reachable_side_effects(entry_tool)
    curr_effects = current.reachable_side_effects(entry_tool)
    escalated = curr_effects - prior_effects
    if escalated:
        reasons.append(
            f"side_effect_escalation:{entry_tool}:{sorted(escalated)}"
        )
    return reasons


def admit_skill_mutation(
    prior: CapabilitySnapshot,
    current: CapabilitySnapshot,
    entry_tool: str,
    behavioral_anomaly_score: float,
    quarantine_threshold: float = 0.72,
) -> None:
    """Hard structural gate runs BEFORE behavioral score is consulted."""
    reasons = detect_capability_delta(prior, current, entry_tool)
    if reasons:
        # Behavioral score is corroboration only; it cannot suppress a structural delta.
        raise CapabilityExpansionError(
            "capability expansion detected; quarantine required "
            f"(reasons={reasons}, behavioral_score={behavioral_anomaly_score:.2f}, "
            f"threshold={quarantine_threshold:.2f})"
        )
    # No structural delta: behavioral drift alone may be logged but never quarantines.
    if behavioral_anomaly_score >= quarantine_threshold:
        # Corroboration path: flag for review WITHOUT capability action.
        print(
            f"[review] behavioral drift only, no capability action "
            f"(score={behavioral_anomaly_score:.2f})"
        )


def _demo() -> None:
    prior = CapabilitySnapshot(
        tools={
            "write_file": ToolSpec("write_file", {"path": "string"}, "write_scoped"),
            "search": ToolSpec("search", {"q": "string", "site": "string"}, "read"),
        },
        edges={"write_file": set(), "search": set()},
    )
    # Injected skill + composition edge that escalates write_file's reachability.
    current = CapabilitySnapshot(
        tools={
            "write_file": ToolSpec("write_file", {"path": "string"}, "write_scoped"),
            "search": ToolSpec("search", {"q": "string", "site": "string"}, "read"),
            "normalize_paths": ToolSpec("normalize_paths", {"paths": "array"}, "read"),
        },
        edges={"write_file": {"normalize_paths"}, "search": set(), "normalize_paths": set()},
    )
    admit_skill_mutation(prior, current, entry_tool="write_file", behavioral_anomaly_score=0.41)


if __name__ == "__main__":
    _demo()
