# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-attack-surface-in-a-live-agent-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-attack-surface-in-a-live-agent-tool-registry.warrant.json
# Markdown SHA-256:   2a077fa3c8c3ddb65f2391315f09995541a3440b7c720903717d0e2fd491e5ee
# Code AST SHA-256:   617f13955a0e116147662bd2cf2d44f9d35c6bab855d2c0552ca5d2acb0f1a23
# Verified Classes:   SkillInjectionBoundaryError, ToolEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a registry entry violates the metadata instruction/description boundary."""


IMPERATIVE_TOKENS = ("always", "you should", "you must", "before calling", "prefer", "then call")
SELF_REFERENCE_OK = True


@dataclass
class ToolEntry:
    name: str
    description: str
    when_to_use: str
    declared_dependencies: set = field(default_factory=set)


def _extract_tool_refs(text: str, known_names: set) -> set:
    return {n for n in known_names if n in text and n != ""}


def validate_registry_entry(entry: ToolEntry, known_names: set) -> None:
    """Grammar gate: metadata may describe itself, never route to another tool."""
    fields = {"description": entry.description, "when_to_use": entry.when_to_use}
    for fname, text in fields.items():
        lowered = text.lower()
        has_imperative = any(tok in lowered for tok in IMPERATIVE_TOKENS)
        refs = _extract_tool_refs(text, known_names) - {entry.name}
        if has_imperative and refs:
            raise SkillInjectionBoundaryError(
                f"Tool {entry.name!r} field {fname!r} contains an imperative "
                f"directive referencing other tools {sorted(refs)}; "
                f"this is a routing instruction, not a capability description."
            )
        if refs - entry.declared_dependencies:
            raise SkillInjectionBoundaryError(
                f"Tool {entry.name!r} field {fname!r} references undeclared "
                f"tools {sorted(refs - entry.declared_dependencies)}."
            )


def check_co_residency(a: ToolEntry, b: ToolEntry, centroid_distance: float,
                       threshold: float = 0.08) -> None:
    """Co-residency gate: high similarity + cross-reference = carrier pattern."""
    if centroid_distance > threshold:
        return
    a_refs_b = b.name in (a.description + a.when_to_use)
    b_refs_a = a.name in (b.description + b.when_to_use)
    if a_refs_b or b_refs_a:
        raise SkillInjectionBoundaryError(
            f"Carrier pattern: {a.name!r} and {b.name!r} co-resident "
            f"(dist={centroid_distance:.3f}) with cross-reference; "
            f"retrieval selection has been subverted."
        )


def audit_call_frequency(tool: str, call_delta: float, consumer_delta: float) -> None:
    """Side-effect monitor: output emitted but never consumed signals exfiltration."""
    if call_delta > 2.0 and consumer_delta < 0.2 * call_delta:
        raise SkillInjectionBoundaryError(
            f"Tool {tool!r} call volume rose {call_delta:.1f}x with no rise in "
            f"output consumers; side-effect injection suspected, quarantine pending audit."
        )
