# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-adversarial-skill-injection-via-behavioral-drift-in-agent-toolchains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-adversarial-skill-injection-via-behavioral-drift-in-agent-toolchains.warrant.json
# Markdown SHA-256:   734b648e39c7976a2418aeb81232ec482ebfe98fc80358c572a3725f54bdd128
# Code AST SHA-256:   cf8243804df6d443ec7a43ddaa5b6b7f0cca75eb535e31fde585d8756b50ff56
# Verified Classes:   SkillInjectionBoundaryError, CapabilityManifest, CallTrace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Dict, List, Optional


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a tool call violates the manifest-conformance predicate."""
    pass


@dataclass(frozen=True)
class CapabilityManifest:
    skill_name: str
    schema_hash: str
    declared_reads: FrozenSet[str]          # context regions the skill may source from
    declares_latent_state: bool             # does the skill emit persistent state fields?
    superset_of: Optional[str] = None       # name of a trusted tool this schema extends


@dataclass
class CallTrace:
    skill_name: str
    schema_hash: str
    # per-argument provenance: arg_name -> {context_region: attribution_fraction}
    provenance: Dict[str, Dict[str, float]]
    emitted_state_fields: List[str] = field(default_factory=list)


TRUSTED_TOOLS: FrozenSet[str] = frozenset({"format_report", "fetch_doc"})


def _schema_hash(schema: dict) -> str:
    return hashlib.sha256(repr(sorted(schema.items())).encode()).hexdigest()


def enforce_manifest_conformance(
    trace: CallTrace,
    manifest: CapabilityManifest,
    baseline: Dict[str, Dict[str, Dict[str, float]]],  # (skill, schema_hash) -> provenance
    undeclared_region_threshold: float = 0.30,
) -> None:
    """
    Fail-closed boundary check. Raises on the conjunction of structural signals
    that has no benign explanation in the observed corpus.
    """

    # Signal 1: undeclared context-region reads.
    undeclared_access = False
    for arg, regions in trace.provenance.items():
        for region, frac in regions.items():
            if region not in manifest.declared_reads and frac > undeclared_region_threshold:
                undeclared_access = True
                break
        if undeclared_access:
            break

    # Signal 2: latent-state emission from a skill that did not declare it.
    latent_emission = bool(trace.emitted_state_fields) and not manifest.declares_latent_state

    # Signal 3: schema superset of a trusted tool (shadowing relationship).
    schema_shadowing = (
        manifest.superset_of is not None
        and manifest.superset_of in TRUSTED_TOOLS
    )

    # Unbaselined schema: a new schema_hash has no provenance baseline, so it
    # must not be treated as conforming by default.
    baseline_key = (trace.skill_name, trace.schema_hash)
    is_unbaselined = trace.skill_name not in baseline or trace.schema_hash not in baseline.get(trace.skill_name, {})

    signals = sum([undeclared_access, latent_emission, schema_shadowing])

    if signals >= 2:
        raise SkillInjectionBoundaryError(
            f"adversarial skill-injection signature: skill={trace.skill_name!r} "
            f"schema={trace.schema_hash[:8]} signals="
            f"[undeclared_read={undeclared_access}, "
            f"latent_emission={latent_emission}, "
            f"schema_shadowing={schema_shadowing}]"
        )

    if is_unbaselined and undeclared_access:
        raise SkillInjectionBoundaryError(
            f"unbaselined skill reading undeclared region: skill={trace.skill_name!r} "
            f"schema={trace.schema_hash[:8]} — quarantined before latent-state entry"
        )

    # Benign path: record provenance into baseline for future conditioning.
    baseline.setdefault(trace.skill_name, {})[trace.schema_hash] = trace.provenance
